I am trying to use a hashset to count the amount of strings in a string array without counting duplicates. However, this program is not working correctly. For eg. this code prints out "4", when in truth their are only 3 unique strings. Does anyone know why this is working incorrectly?
String centers[]=new String[1000];
/* Only for Testing Purposes*/
centers[0] = "Soccer";
centers[1] = "Soccer";
centers[2]= "Baseball";
centers[3] = "Table Tennis";
centers[4] = "Soccer";
List<String> centerList = Arrays.asList(centers);
Set<String> uniqueCenters = new HashSet<String>();
uniqueCenters.addAll(centerList);
Integer numberOfUniqueStrings = uniqueCenters.size();
System.out.println(numberOfUniqueStrings);
Just a guess, but centers
has 1000 elements, and you only set 5 of them. Maybe the other 995 are null
, giving you a HashSet with one more element than you expect (null
).
You can easily test this by printing the contents though:
for (String s : uniqueCenters) {
System.out.println("Got element: " + s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With