
假设您没有覆盖
equals始终返回true
的方法,它们将放置在地图的链接列表结构中。不同的键可能具有相同的hashCode,但是如果所有键都具有相同的hashCode,则您的HashMap将成为链接列表,这首先使使用此结构的目的无效。
您可以在
HashMap实现中亲自看到它:
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); // hash would always be the same if hashCode is constant int i = indexFor(hash, table.length); // i would always be the same if hashCode is constant for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { // the key is searched using the // equals method V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null;}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)