在Java中对具有相同哈希码的对象进行排序 [英] Sorting objects with the same hashcode in java
问题描述
例如,如果我正在对整数进行哈希处理,而我的哈希函数只是(n%10),则数字17和数字27将产生相同的结果.这并不意味着这些数字相同.
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.
现在,假设n%10是我的哈希函数,我的问题是: 如果我按以下顺序输入以下数字,由于数字按其哈希码排序,该如何输出?
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 ?
数字:10、27、17、38、58、28、43
Numbers: 10, 27, 17, 38, 58, 28, 43
推荐答案
我想您可能对hashCode()
在Java中的用途感到困惑.
I think you may be confused as to what hashCode()
is used for in Java.
排序通常不依赖于equals()
和hashCode()
.它们用于识别平等.例如,HashSet
将使用这两种方法仅标识相等性. TreeSet
还使用这两种方法来标识相等性,但是它们并不用于对元素进行排序.
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.
排序需要一种比较对象的方法,为此(仅考虑Java SE),要么需要该类实现Comparable
并因此具有compareTo(Object o)
方法,要么需要提供Comparator
进行排序算法.
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.
因此,假设您正在使用Java SE中的方法(例如Arrays.sort()
)对整数进行排序,则将不考虑hashCode
,并且您的整数将根据类或提供的compareTo()
得出Comparator
.
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
.
这篇关于在Java中对具有相同哈希码的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!