简体   繁体   中英

Sorting objects with the same hashcode in java

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM