哈希码会给出负值吗?

问题描述 投票:0回答:1

在给出的代码中,它试图通过使用另一种方法linearprobe检查任何冲突来为哈希表提供有效的索引。我只是感到困惑,为什么我们需要检查索引<0,所以会出现hashCode为负的实例吗?什么时候/为什么会发生?

private int getHashIndex(K key)
{
   //1.convert key to hashcode, then get the index;
  //2. then use linear probing to check for the correct index;
  int index = key.hashCode() % hashTable.length; 
  if(index < 0) { //So a hash code can be negative?
    index += hashTable.length;
  }

  index = linearProbe(index,key);

  return index;

}
java hash hashtable hashcode
1个回答
1
投票

是,如果给定的字符串足够长,则其哈希码将大于可以存储在32位CPU上的最大整数。因此,在这种情况下,由于整数溢出,hashCode返回的值可以为负。

ref:https://www.cs.cmu.edu/~adamchik/15-121/lectures/Hashing/hashing.html

希望它有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.