1

How do I check if an ArrayList<int[]> contains a given array [x, y]? I have found the same question in c#, but can't find any answers for java.

At the moment I am using myList.contains(myArray) but it is always evaluating to false, I assume for similar reasons as in C#. The solution in C# is to use LINQ, which does not exist in java.

Is there another way I can do this or will I have to write my own subroutine to pull out the values of each list element and compare them manually?


Edit: I've written my own subroutine to do this which works (assuming each array has two elements), but a more elegant solution would be appreciated

private boolean contains(List<int[]> list, int[] array) {
    for (int[] listItem : list) {
        if (listItem[0] == array[0] &&
           listItem[1] == array[1]) {
            return true;
        }
    }
    return false;
Aric
  • 319
  • 7
  • 27
  • A remark: du to the fact that generics are invariant and erased, and arrays are covariant and retained, mixing them sets you up for trouble. – Turing85 Nov 09 '19 at 18:35

2 Answers2

1

The .contains method compares each object with .equals which as this answer points out just compares the identity of the array objects (i.e. checks if they're the same Java object), it does not compare the contents of the arrays.

What you need to do is to write a for loop, check each element with Arrays.equals(..) (which compares the contents of the arrays). For example:

boolean found = false;
for (int i = 0; i < myList.size(); i++)
    if (Arrays.equals(myArray, myList.get(i)) found = true;
Adrian Smith
  • 17,236
  • 11
  • 71
  • 93
1

There is Arrays.equals, and also Streams, which are designed for similar use cases as LINQ. In this case, the Stream.anyMatch method is very similar to Any in LINQ.

Combining these two, you can write your method in one statement:

private boolean contains(List<int[]> list, int[] array) {
    return list.stream()
        .anyMatch(x -> Arrays.equals(x, array));
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313