Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Hashsets to Count Amount of Strings in Array without Duplicates

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);
like image 608
user3474775 Avatar asked Mar 20 '23 18:03

user3474775


1 Answers

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);
}
like image 149
Brendan Long Avatar answered Apr 20 '23 01:04

Brendan Long