【问题标题】:will an hashcode ever give a negative value? [duplicate]哈希码会给出负值吗? [复制]
【发布时间】:2020-04-01 22:19:30
【问题描述】:

在给出的代码中,它试图通过使用另一种方法 linearprobe 检查任何冲突来为哈希表提供有效索引。我只是对为什么我们需要检查 index

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】:

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

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

    希望对您有所帮助!

    【讨论】:

    • 根据哈希函数,“足够长”可以是两个或三个字符。
    • 字符串之外还有其他对象。例如。 Integer.valueOf(-1).hashCode()的负散列很容易预测...
    猜你喜欢
    • 1970-01-01
    • 2020-07-18
    • 2012-09-16
    • 2011-09-15
    • 2019-03-19
    • 1970-01-01
    • 2012-02-19
    • 2015-07-01
    • 2021-05-26
    相关资源
    最近更新 更多