【问题标题】:Getting index of a key in a Hashtable in Java在Java中获取哈希表中键的索引
【发布时间】:2014-05-18 01:30:07
【问题描述】:

我正在编写一个 Dictionary 类的实现。我目前正在写add方法

(public Vadd(K键,V值))

算法:

if the table is too full
    rehash
grab the index based on the key
probe with the index and key to resolve collisions
if the table at the index is null, or has been removed
    increment the number of entries
    increment the number of locations used
    set the table at that index to a new tableentry
else
    grab the value currently at that index
    set the value at the index to the new value
return the old value

我不知道如何根据提供的键获取索引。我也不知道如何引用 Hashtable 中的特定索引。

谢谢

【问题讨论】:

  • 每个 Java 对象都有一个 hashCode() 方法:docs.oracle.com/javase/7/docs/api/java/lang/…。如果您打算将您的对象用作哈希表中的键,那么您应该覆盖 both 此方法 equals(Object) 方法。
  • 哈希表的索引取决于哈希函数以及每个键的哈希码。

标签: java algorithm dictionary key hashtable


【解决方案1】:

假设您出于某种原因从头开始重新实现字典/哈希表(如果您不是,并且使用哈希表 - 那么您引用的算法完全不合适)。

实现支持数组的哈希表的经典方法是计算键的哈希值,然后将值放入该键的数组索引模数数组大小(在以任何方式考虑冲突之后)。

因此,“根据键获取索引”将是 index = hash(key) % backing_array_length;

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 2014-01-30
    • 2013-04-04
    • 2018-08-29
    • 2013-02-12
    • 2013-06-27
    • 2018-05-29
    • 1970-01-01
    • 2012-01-10
    相关资源
    最近更新 更多