Arthur
Arthur

Reputation: 171

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

Upvotes: 0

Views: 265

Answers (1)

Scratte
Scratte

Reputation: 3166

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.

Upvotes: 1

Related Questions