4

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);

2 Answers 2

6

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or just print the Set: [null, Table Tennis, Soccer, Baseball]. And indeed this is the case since HashSet allows null.
1

The problem is with this statement:

String centers[]=new String[1000];

You're creating a String array with 1000 elements. In java, instantiating an array also assigns a default value to the elements of the array, in this case, the elements all have a null value.

That's why when you create a HashSet of that array, you're essentially getting "Soccer", "Baseball", "Table Tennis", and null.

edit:

You can remove the null entry in your HashSet by calling uniqueCenters.remove(null);

1 Comment

This is pretty awful looking code however the reason given is correct. A Set, by definition, will not allow duplicates, however it will allow (one and only one) null. Therefore the output value is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.