Skip to content
Advertisement

Check if ArrayList Contains same array order ignored

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

Advertisement

Answer

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);
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement