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

前端 未结 4 1658
广开言路
广开言路 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条回答
  • 2021-01-23 10:07

    REFER -> https://stackoverflow.com/a/106351/1897935

    ArrayList<Object> list = ...;
    for (Object o : list) {
            if (o.getClass().equals(Integer.TYPE)) {
                handleInt((int)o);
            }
            else if (o.getClass().equals(String.class)) {
                handleString((String)o);
            }
            ...
        }
    
    0 讨论(0)
  • 2021-01-23 10:15

    A list of arrays stores only the references to the arrays, not their content, therefore contains() is only able to say, if the list contains the exact reference to the array you input. It doesn't evaluate the contents of the array.

    If you need to check, if the list contains an array with specific values, you will have to iterate over the list and use Arrays.equals(arr1, arr2).

    0 讨论(0)
  • 2021-01-23 10:24

    You cannot because

        int[] a = { 1,2,3 };
        int[] b = { 1,2,3 };
        List<int[]> list = new ArrayList<int[]>();
        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<int[]> list = new ArrayList<int[]>();
        list.add(a);
        list.contains(a); // is true
    
    0 讨论(0)
  • 2021-01-23 10:30

    You cannot, unfortunately. I would probably wrap the array in another object and put that in the list instead. Something like (totally untested):

    public class IntArrayWrapper {
        private final int[] intArray;
        public IntArrayWrapper(int[] intArray) {
            this.intArray = intArray;
        }
        @Override
        public int hashCode() {
            return Arrays.hashCode(intArray);
        }
        @Override
        public boolean equals(Object other) {
            return other instanceof IntArrayWrapper && Arrays.equals(this.intArray, ((IntArrayWrapper) other).intArray);
        }
    }
    

    Then, if you decide in the future to replace your ArrayList with a HashSet, for example, it will be simple (and you might get some nice performance gains).

    0 讨论(0)
提交回复
热议问题