How can I find if my ArrayList of int[] contains an int[]

前端 未结 4 1659
广开言路
广开言路 2021-01-23 09:58

I have an ArrayList containing int[].

Assuming Arrays.equals(int[], (a value in the arrayList)) = true

why when I do

4条回答
  •  -上瘾入骨i
    2021-01-23 10:24

    You cannot because

        int[] a = { 1,2,3 };
        int[] b = { 1,2,3 };
        List list = new ArrayList();
        list.add(a);
        list.contains(b); // is false
    

    a is not equal b, it means a.equals(b) will return false. Method Collection.contans(Object) is using equals to check if an abject is already in a collections. So if a.equals(b) is false you get that the array is not in the collection even if they looks the same.

    There is an exception. If they are really the same object contains will return true. See below:

        int[] a = { 1,2,3 };
        List list = new ArrayList();
        list.add(a);
        list.contains(a); // is true
    

提交回复
热议问题