Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList contains method doesn't work

So when I run this program it shows that the ArrayList "test" doesn't contain the array [5,6] inside the variable "position".When I checked the output, it is clearly in there and i see that "test" does contain that element.


Output:

[5, 6] [5, 6] false

Code:

package arraylisttest;

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListTest {
    public static void main(String[] args) {
        int[] position = { 5, 6 };
        ArrayList<int[]> test = new ArrayList<>();

        test.add(new int[] {50, 2});
        test.add(new int[] {0, 7});
        test.add(new int[] {5, 6});
        test.add(new int[] {2, 1});

        System.out.println(Arrays.toString(position));
        System.out.println(Arrays.toString(test.get(2)));
        System.out.println(test.contains(position));
    }
}
like image 919
StackOverflowAccount Avatar asked Jul 30 '26 12:07

StackOverflowAccount


2 Answers

I believe that List.contains() will use the equals() method to determine if the list contains a given object (q.v. the source code for ArrayList#contains()). It will not compare the two points in each 2D array to see if they be the same. So even though the point {5, 6} logically appears in the list, it is a different object than position which you are using for the comparison, and hence the comparison fails.

Note that the following code would have behaved as you expected:

int[] position = { 5, 6 };
ArrayList<int[]> test = new ArrayList<>();
test.add(new int[] {50, 2});
test.add(new int[] {0, 7});
test.add(position);
test.add(new int[] {2, 1});

System.out.println(Arrays.toString(position));
System.out.println(Arrays.toString(test.get(2)));

System.out.println(test.contains(position));
like image 191
Tim Biegeleisen Avatar answered Aug 02 '26 02:08

Tim Biegeleisen


The problem here is that arrays don't override Object#equals method hence the output you're receiving; rather you can create ArrayList of ArrayLists instead e.g. the code below will output true.

ArrayList<Integer> position = new ArrayList<>(Arrays.asList(5, 6));
ArrayList<ArrayList<Integer>> test = new ArrayList<>();
ArrayList<Integer> y = new ArrayList<>(Arrays.asList(5,6));
test.add(y);
System.out.println(test.contains(position));

another option would be to leave your current solution as it is, but use a stream to perform a comparison against the other arrays within the list:

System.out.println(test.stream().anyMatch(e -> Arrays.equals(e,position)));
like image 38
Ousmane D. Avatar answered Aug 02 '26 02:08

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!