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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With