Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Set<int[]> vs Set<List<Integer>>

I have following code to use int[] and List<Integer> as hashset element, however, they have different result. Why List<Integer> could be used to compare hash, but array not?

Set<List<Integer>> set2 = new HashSet();
set2.add(Arrays.asList(1, 2, 3, 4));
System.out.println(set2.contains(Arrays.asList(1, 2, 3, 4)));


int[] arr1 = {1, 2, 3, 4};
int[] arr2 = {1, 2, 3, 4};
Set<int[]> set3 = new HashSet();
set3.add(arr1);
System.out.println(set3.contains(arr2));

The output is

true
false
like image 551
Thomas Avatar asked Jul 08 '18 17:07

Thomas


1 Answers

Simple: because array equals does not compare contents. If you want to do that, you have to use Arrays.equals(array1, array2) (see this question), which of course isn't possible when using a Set (which will automatically use array1.equals(array2)).

That array1.equals() is doing a reference comparison. In other words: when using the method on arrays, you actually do use == under the covers! And you have two different arrays there, so they are not equal from the array perspective.

Lists on the other hand do an element by element comparison! Therefore two different list objects but the list have equal content.

like image 79
GhostCat Avatar answered Sep 21 '22 16:09

GhostCat