user3880174
user3880174

Reputation: 15

Remove duplicate arrays in a ArrayList?

Is there a way to remove duplicates arrays in an ArrayList?
I tried to convert the ArrayList into a HashSet and back to remove the duplicate arrays.
But this won't work:

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

mylist.add(new int[]{1,2});
mylist.add(new int[]{2,2}); // Duplicate
mylist.add(new int[]{2,2}); // Duplicate

Before:

{{1,2},{2,2},{2,2}}

After:

{{1,2},{2,2}}

Upvotes: 0

Views: 373

Answers (2)

Brett Okken
Brett Okken

Reputation: 6306

This cannot be done with an ArrayList, this could be done with a TreeSet and a custom Comparator implementation which is able to accurately compare the int[] objects.

For example:

public final class IntArrayComparator implements Comparator<int[]>
{
    public int compare(int[] a, int[] b)
    {
        if (a == null)
            return b == null ? 0 : 1;

        if (a.length != b.length)
            return a.length - b.length;

        for (int i=0; i<a.length; ++i)
        {
            final int diff = a[i] - b[i];
            if (diff != 0)
                return diff;
        }

        return 0;
    }
}

Upvotes: 0

laune
laune

Reputation: 31290

Different array objects have different hashCode() values even if their contents are equal.

Offhand, I can't think of anything better than to wrap the arrays into a class and to hash all wrapped arrays using a hashCode based on the value and the Arrays.equals as an equals.

This would be O(n) as opposed to searching for duplicates in a nested loop (O(n^2)).

Upvotes: 2

Related Questions