0

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}}
Unihedron
11.1k13 gold badges65 silver badges72 bronze badges
asked Jul 26, 2014 at 16:59
6
  • 1
    What defines a duplicate? '2' or int[]{2,2}? Commented Jul 26, 2014 at 17:06
  • Check if your Arraylist contains an Array before adding it Commented Jul 26, 2014 at 17:06
  • extend ArrayList and override add/addAll methods by checking first if the new item already exists in the list Commented Jul 26, 2014 at 17:18
  • @xgeorgekx Ok, I gonna try this out using a hashCode based on the value (@laune ´s idea) Commented Jul 26, 2014 at 17:27
  • javarevisited.blogspot.in/2012/12/… Commented Jul 26, 2014 at 17:31

2 Answers 2

2

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

answered Jul 26, 2014 at 17:06

2 Comments

I am gonna check with Arrays.equals a duplicate before adding it. Also thanks to @xgerogekx.
Preventing the evil is alway best ;-) Although, it'll be costly and costlier with increasing list length.
0

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;
 }
}
answered Jul 26, 2014 at 17:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.