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

2
  • See: stackoverflow.com/questions/20616242/… Commented Apr 3, 2022 at 1:08
  • @zysaaa That question is comparing two arrayList<int[]>, while im trying to check if an int[] is contained in the arrayList<int[]> ignoring the order. Commented Apr 3, 2022 at 1:14

1 Answer 1

-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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.