问题
For example, if I am hashing integers and my hashing function is simply (n % 10) then the number 17 and the number 27 will produce the same result. This does not mean that those numbers are the same.
Now, assuming the n%10 is my hashing function, my question is: If I input the following numbers by the following order, how will the numbers be outputed since they are sorted by their hashcode ?
Numbers: 10, 27, 17, 38, 58, 28, 43
回答1:
I think you may be confused as to what hashCode()
is used for in Java.
Sorting does not generally rely on equals()
and hashCode()
. They're used to identify equality. For example HashSet
will use these two methods to identify equality only. TreeSet
also uses both methods to identify equality, but they're not used to sort the elements.
Sorting needs a way to compare objects, and for that (only considering Java SE) it's either required that the class implements Comparable
and therefore has a compareTo(Object o)
method, or that a Comparator
is provided for the sorting algorithm.
So assuming you're sorting the integers using a method in Java SE, like Arrays.sort()
, then the hashCode
will not be considered and your integers will come out according to the compareTo()
of the class or a provided Comparator
.
来源:https://stackoverflow.com/questions/59973475/sorting-objects-with-the-same-hashcode-in-java