1

I juste learned JAVA and I have a problem with this code :

HashSet myHashSet = new HashSet();

int[] tab1 = new int[] {0,0};
int[] tab2 = new int[] {0,0};

myHashSet.add(tab1);
myHashSet.add(tab2);

Now my HashSet contains {{0;0};{0;0}}! How can I manage simply to not have duplicates in this case? I thought HashSet didn't allow duplicates.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Mieus
  • 306
  • 1
  • 3
  • 7

2 Answers2

2

HashSet doesn't allow duplicated based on hashCode and equals methods, but arrays don't override such methods, so even if you have two arrays with the same content, they are not the same arrays, so they will be allowed in a Set.

Use List<Integer> instead. Note the usage of Integer over int because generics don't support primitive types.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Another, more efficient option is to wrap each `int` array in an [IntBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/IntBuffer.html). – VGR Aug 04 '14 at 21:30
0

Two arrays, even if they contain the same elements, may not be equal, because equality is defined as reference-equality for non-primitives.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57