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.
Use
equals()onString(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:
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.