Java 当hashcode()返回零时,对集合实现有什么影响
好的,仅就知识而言,如果Java 当hashcode()返回零时,对集合实现有什么影响,java,collections,hashcode,Java,Collections,Hashcode,好的,仅就知识而言,如果对象的hashcode方法在demoClass中总是返回0,那么它对集合实现类(如hashmap、hashset等)有什么意义。我知道它与hashmap的putForNullKey或其他类的集合实现有关,但不知道太多细节。我知道对于空对象,hascode是0,因此它对0 hashcode有特定的方法 @Override public int hashCode() { return 0; } 这将使HashMap、HashSet和其他依赖hashCode的集合效率非常低
对象的hashcode
方法在demoClass
中总是返回0
,那么它对集合实现类(如hashmap
、hashset
等)有什么意义。我知道它与hashmap的putForNullKey
或其他类的集合实现有关,但不知道太多细节。我知道对于空对象,hascode是0
,因此它对0 hashcode有特定的方法
@Override
public int hashCode() {
return 0;
}
这将使HashMap
、HashSet
和其他依赖hashCode
的集合效率非常低,因为所有元素/条目都将添加到同一个bin
诸如get()
、containsKey()
和contains()
等方法将采用O(n)
而不是O(1)
顺便说一句,答案并不特定于0hashCode
。任何常量hashCode
的行为都会完全相同。其他结构如Set
?@BhargavModi I提到HashSet。并非所有Set实现都使用hashCode。