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

Kai Liu :

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
GhostCat salutes Monica C. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92008&siteId=1