Вопрос

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top