The problem is, ArrayList#containts
is using Object#equals
whose default operation works like this == obj
myArray
and checkFor
are two different objects, they have nothing in common.
For example System.out.println(myArray == checkFor);
will print out false
. You can test this further by doing...
checkFor[1] = 3;
System.out.println(Arrays.toString(myArray));
System.out.println(Arrays.toString(checkFor));
Which will output:
[2, 1]
[2, 3]
So clearly, the two arrays have nothing in common and therefore aren't equal in any way...
However...
System.out.println(visited.contains(myArray));
Would output true
or
int[] myArray = {2, 1};
visited.add(myArray);
int[] checkFor = myArray;
System.out.println(visited.contains(checkFor));
Would output true
...
You could also use Arrays.equals(myArray, checkFor)
About the only way I know that you might be able to make this work, would be iterate the List
and use Arrays.equals
, for example...
public class TestArrayCollection {
public static void main(String[] args) {
List<int[]> visited = new ArrayList<int[]>();
int[] myArray = {2, 1};
visited.add(myArray);
int[] checkFor = {2, 1};
System.out.println(contains(visited, checkFor));
}
public static boolean contains(List<int[]> values, int[] match) {
boolean contains = false;
for (int[] element : values) {
if (Arrays.equals(element, match)) {
contains = true;
break;
}
}
return contains;
}
}