哈希表.怎么运行的? [英] Hashtable. How it works?

查看:64
本文介绍了哈希表.怎么运行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在尝试了解如何构造Hashtable.

Now, I'm trying to understand how to construct the Hashtable.

最有趣-将对象添加到Hashtable?

The most interesting - as objects are added to the Hashtable?

我读过一本书,

第一步: 计算的hashCode()对象.

at first step: Calculated hashCode() object.

接下来,我们确定该对象在Hashtable:obj.hashCode() % Hashtable.length中的位置.

Next, we determine the position of this object in the Hashtable: obj.hashCode() % Hashtable.length.

例如,将更多元素添加到Hashtable:

For example, add more elements to the Hashtable:

Hashtable<String, String> hm=new Hashtable<String, String>(100);

        hm.put("Lee","Lee");
        hm.put("lee","lee");
        hm.put("eel","eel");

定义将对象放置在其中的存储桶:

Define a bucket into which is placed the object:

    System.out.println("Lee".hashCode() % 100);
    System.out.println("lee".hashCode() % 100);
    System.out.println("eel".hashCode() % 100);

如果我了解算法,则必须将对象放在表中,如下所示:

If I understand the algorithm, the objects must be placed in the table as follows:

eel /*because,"eel".hashCode() % 100=0*/, 
lee /*because, "lee".hashCode() % 100=20*/, 
Lee /*because, "Lee".hashCode() % 100=68*/

但是我们看到的结果是什么?

but what we see as a result?

System.out.println(hm);

{Lee=Lee, lee=lee, eel=eel} 

请告诉我,我哪里出错了?

Please, tell me, where did I go wrong?

推荐答案

不能保证Hashtable(以及HashMap)元素的迭代顺序(取决于实现),所以恕我直言,试图这样做没有太多意义在此基础上建立理论.它甚至可能在不同的Java版本之间发生变化(它确实从Java5更改为Java6).

The iteration order of Hashtable (as well as HashMap) elements is not guaranteed (implementation dependent), so IMHO there is not much point trying to build a theory on it. It may even change between different Java versions (it did change from Java5 to Java6).

顺便说一句Hashtable已过时,建议改为使用(并分析)HashMap.

Btw Hashtable is obsolete, it is recommended to use (and analyse) HashMap instead.

您的描述对我来说是基本的哈希映射实现.但是,HashMap的实际实现比这要复杂得多,至少从Java4开始.例如.哈希表的大小始终是2的幂(对于您所描述的基本哈希表来说,这是一个非常糟糕的决定),并且将从键对象获得的哈希值在内部进行重新哈希处理,以实现在实际大小上的更均匀分布的桌子.有关此内容的更多详细信息,请参阅以下Java专家通讯期刊:

Your description sounds OK to me as a basic hash map implementation. However, the actual implementation of HashMap is quite a bit more sophisticated than that, at least since Java4. E.g. the size of the hash table is always a power of two (which would be quite a bad decision for a basic hashtable like you describe), and hash values got from the key objects are rehashed internally to achieve a more even distribution over the actual size of the table. For more details on this, see the following issues of the Java Specialist Newsletter:

  • HashMap requires a better hashCode()
  • Follow-up to JDK 1.4 HashMap hashCode() mystery

这篇关于哈希表.怎么运行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆