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

前端 未结 4 1655
广开言路
广开言路 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: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).

提交回复
热议问题