0

i have an array of strings, it is unsorted and it has duplicate elements. i want to count the distinct elements,but when i call my method it returns number of all elements, not just the distinct ones. any idea please?

public static double countDistinctString(String[] array) {
        double distinctStrings = 0; 
        for (int j = 0; j < array.length; j++){ 
            String thisString = array[j]; 
            boolean seenThisStringBefore = false; 
            for (int i = 0; i < j; i++){ 
                if (thisString == array[i]){ 
                    seenThisStringBefore = true; 
                } 
            } 
            if (!seenThisStringBefore){ 
                distinctStrings++; 
            } 
        } 
        return distinctStrings; 
    }
}
Vitruvie
  • 2,327
  • 18
  • 25
Najme
  • 5
  • 2

2 Answers2

0

The problem is that you're using == to compare strings; see How do I compare strings in Java? for why this doesn't work. Use if (thisString.equals(array[i])) instead.

Community
  • 1
  • 1
Vitruvie
  • 2,327
  • 18
  • 25
0

This should work (I've also improved it a bit - using int instead of double, using break once found the match):

public static double countDistinctString(String[] array) {
    int distinctStrings = 0; 

    for (int j = 0; j < array.length; j++) { 
        String currentString = array[j]; 
        boolean seenThisStringBefore = false; 

        for (int i = 0; i < j; i++){ 
            if (currentString.equals(array[i])) { 
                seenThisStringBefore = true;
                break;
            } 
        }

        if (!seenThisStringBefore) { 
            distinctStrings++; 
        } 
    }

    return distinctStrings; 
}
Benny Bauer
  • 1,035
  • 1
  • 6
  • 19