Can anyone please explain this code to me, I don’t have much coding experience with Collections so I am having difficulties in understanding these LOC.
String[] stringList ={"1","2","1","1","2","3","2","3","2","1"};
List<String> al =Arrays.asList(stringList);
Set<String> uniqueList = new HashSet<String>(al);
for (String strCount :uniqueList) {
System.out.println(strCount + ": " + Collections.frequency(al, strCount));
}
Why does this loop only run 3 times while uniquelist has all the members of stringList. Shouldn’t the loop run 10 times (length of uniqueList)?
The for loop only executes three times, because there are only 3 distinct values in your
stringList.A
Setdoes not allow duplicate entries. TheSetchecks entries with.equals(), which will betruefor two duplicate entries. Consequently, there are only three elements inuniqueList, namely:"1","2"and"3".Note, that
"2".equals("2")istrue.Here is the most important part of the javadoc: