Using contains on an ArrayList with integer arrays

Solution 1:

Arrays can only be compared with Arrays.equals().

You probably want an ArrayList of ArrayLists.

ArrayList<ArrayList<Integer>> j = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> w = new ArrayList<Integer>();
w.add(1); w.add(2);
j.add(w);
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(1); t.add(2);
return j.contains(t); // should return true.

Solution 2:

The problem here is that arrays don't override Object.equals(Object), So the comparison between two list entries happens with the default equals() implementation

// from Object.class
public boolean equals(Object obj) {
return (this == obj);
}

So you have to iterate over the list and check all entries using Arrays.equals(int[], int[]). Here's a Helper method that does this:

public static boolean isInList(
    final List<int[]> list, final int[] candidate){

    for(final int[] item : list){
        if(Arrays.equals(item, candidate)){
            return true;
        }
    }
    return false;
}

Update: Ever since Java 8, this has got a lot simpler:

public static boolean isInList(
        final List<int[]> list, final int[] candidate) {

    return list.stream().anyMatch(a -> Arrays.equals(a, candidate));
            //  ^-- or you may want to use .parallelStream() here instead
}