有一些来自 Thinking in Java 的代码:
public class SimpleHashMap<K,V> extends AbstractMap<K,V> {
static final int SIZE = 997;
@SuppressWarnings("unchecked")
LinkedList<MapEntry<K,V>>[] buckets = new LinkedList[SIZE];
public V put(K key, V value) {
V oldValue = null;
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null)
buckets[index] = new LinkedList<MapEntry<K,V>>();
LinkedList<MapEntry<K,V>> bucket = buckets[index];
// ...
}
// ...
}
int index = Math.abs(key.hashCode()) % SIZE;
字符串有什么意义?为什么使用完全绝对值和模数运算?
答案 0 :(得分:2)
此表达式计算固定大小数组中的索引。
索引必须是非负数且小于数组的长度。
int index = Math.abs(key.hashCode()) % SIZE;
方法hashCode()
可以返回一个负数值,其绝对值超过数组的长度。因此,此代码采用其绝对值,并使用模数运算符将任何过大的值包装到数组中的位置。
例如,假设hashCode()
值为-1000。来自Math.abs()
的绝对值是1000.然后取1000%SIZE(其中SIZE为997)给出3.因此索引将为3,指向从零开始的数组中的第四个桶。
答案 1 :(得分:2)
请记住,index
将用作数组索引。因此,使用&#34; raw&#34;哈希码是不可接受的,因为返回值可能是负数,也可能是SIZE-1
以上的正数。
当然,可以开发确保指数在范围内的其他方法。例如,可以先计算模数,然后将SIZE
添加到负数。