Java ArrayList contains a method that doesn't work

So when I run this program, it shows that the "test" ArrayList does not contain the array [5,6] inside the "position" variable. When I checked the output, it is clearly there and I can see that "test" contains 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));
    }
}

      

+3


source to share


3 answers


I believe I List.contains()

will use a method equals()

to determine if the list contains a given object (qv source code for ArrayList # contains () ). It will not compare the two points in each 2D array to make sure they are the same. Thus, although the point {5, 6}

logically appears in the list, it is a different object than the position

one you are using for the comparison and hence the comparison fails.

Please note that the following code will behave 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));

      

+3


source


The problem is that arrays don't override Object#equals

, hence the output you get; rather, you can create ArrayList from ArrayLists rather than eg. the code below will return 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 is to leave your current solution as it is, but use a stream to compare against other arrays in the list:

System.out.println(test.stream().anyMatch(e -> Arrays.equals(e,position)));

      

+2


source


Arrays can only be compared to Arrays.equals () arrays.

You should use ArrayList instead:

ArrayList<Integer> position = new ArrayList<Integer>(Arrays.asList(5, 6));

ArrayList<ArrayList<Integer>> test = new ArrayList<>();
test.add(new ArrayList<>(Arrays.asList(50, 2)))
test.add(new ArrayList<>(Arrays.asList(0, 7)));
test.add(new ArrayList<>(Arrays.asList(5, 6)));
test.add(new ArrayList<>(Arrays.asList(2, 1)));


System.out.println(test.contains(position));

      

0


source







All Articles