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;
字符串有什么意义?为什么使用绝对值和模运算?
最佳答案
请记住,index
将用作数组索引。因此,使用“原始”哈希码是 Not Acceptable ,因为返回值可能是负数,也可能是 SIZE-1
以上的正数。
- 使用绝对值保证数字非负
- 模数用于确保索引在允许的数组索引范围内。
当然,可以开发其他确保索引在范围内的方法。例如,可以先计算模数,然后将 SIZE
添加到负数。
关于java - 在此 HashMap 实现中使用此类操作有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39707924/