0

I've initialized an ArrayList holding int arrays as such:

ArrayList<int[]> holder = new ArrayList<int[]>();

If I add an int[] like this:

int[] first = {1, 2, 3};

holder.add(first);

If I do this check, I want the function to return true, but it returns false right now

int[] second = {2, 1, 3};

if(holder.contains(second)) return true;

else return false

  • See: https://stackoverflow.com/questions/20616242/comparing-equality-of-2-arraylistint-with-equals – zysaaa Apr 03 '22 at 01:08
  • @zysaaa That question is comparing two arrayList, while im trying to check if an int[] is contained in the arrayList ignoring the order. – Ahmad Louis Apr 03 '22 at 01:14

1 Answers1

-1

You can't use ArrayList#Contains to judge since int[] don't have a special equals. You can iterate list and then compare:

    private static boolean contains(ArrayList<int[]> holder, int[] arr) {
        for (int[] item : holder) {
            if (equals(item, arr)) {
                return true;
            }
        }
        return false;
    }

    // from https://stackoverflow.com/questions/10154305/java-checking-equality-of-arrays-order-doesnt-matter
    private static boolean equals(int[] arr1, int[] arr2) {
        int[] copyOfArr1 = Arrays.copyOf(arr1, arr1.length);
        int[] copyOfArr2 = Arrays.copyOf(arr2, arr2.length);
        Arrays.sort(copyOfArr1);
        Arrays.sort(copyOfArr2);
        return Arrays.equals(copyOfArr1, copyOfArr2);
    }
zysaaa
  • 1,777
  • 2
  • 8
  • 19
  • Bad answer. It mutates the arrays as a side effect fever of calling `equals()`, and all unexpected/unadvertised side effect are very bad. Might as well just sort all the array's first, then use plain `contains()` – Bohemian Apr 03 '22 at 02:41