1

I don't know what I'm doing wrong, I have two lists of items and am trying to compare both of them.

private static void check_results(ArrayList<int[]> result2, int[] reversedList) {
    //check results list for matches
    System.out.println();
    for (int[] item : result2) {
        System.out.println(Arrays.toString(item) + " compared to " + Arrays.toString(reversedList));
        if ( Arrays.toString(item) == Arrays.toString(reversedList)) 
        {   
            System.out.println("we have a match!");
        }
    }

}

but I never seem to have a match. When I visibly compare, I can see they are matches.

[0, 0, 0, 20] compared to [0, 0, 0, 20]
... and so on

What am I doing wrong? I know result2 starts as an ArrayList but I iterate thought it so its a int[] just like my variable reversedList but I never get a match.

Lostsoul
  • 25,013
  • 48
  • 144
  • 239

3 Answers3

4

Use equals() on String (see the exact definition here), == compares by reference (i.e., the two reference you have are pointing to exactly the same object in memory), not by value (you may have multiple string instances in the memory having the same content).

What you need is this:

if ( Arrays.toString(item).equals( Arrays.toString(reversedList) )) { ... }

String might be optimized, or might not, you can never know for sure (ok, in some cases defined by the JLS, e.g., when two Strings are defined in the same compilation unit, and their value is exactly the same without any additional compile-time verification, they will use the same reference, but using for instance "ab" and "a" + "b" might be either the same or different references, based on your OS, JVM version, build number, the current state of the cosmos, etc.).

See some additional notes here or here.

Community
  • 1
  • 1
rlegendi
  • 10,466
  • 3
  • 38
  • 50
2

Comparing Objects (which Strings are) using == checks that they're the exact same object. To put it another way, that they refer to the same location in memory. You want to use the .equals() method instead.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
2

Don't compare String with == it compares references of (String) objects for meaningful comparision use equals or equalsIgnoreCase method.

Instead of

if ( Arrays.toString(item) == Arrays.toString(reversedList)) 

Use this :

if (Arrays.toString(item).equals(Arrays.toString(reversedList)))

or this if you want case insensitive comparison

if (Arrays.toString(item).equalsIgnoreCase(Arrays.toString(reversedList))) 
mprabhat
  • 20,107
  • 7
  • 46
  • 63