A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 伍淑江 中级黑马   /  2013-3-28 01:39  /  1929 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 伍淑江 于 2013-3-28 21:50 编辑

hashtable可以有重复的键和值吗?

评分

参与人数 1技术分 +1 收起 理由
黄玉昆 + 1

查看全部评分

3 个回复

倒序浏览
不能包含重复的键,每个键最多只能映射到一个值。
回复 使用道具 举报
呵呵,以前还没有注意。看了看hashtable的代码,才发现这里有不少东西啊
这是hashtable中的put方法,与大家分享一下:
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                V old = e.value;
                e.value = value;
                return old;
            }
        }

        modCount++;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        Entry<K,V> e = tab[index];
        tab[index] = new Entry<K,V>(hash, key, value, e);
        count++;
        return null;
    }

总结一下:
1、与hashmap的不同点是否是同步的方法
2、与hashmap的不同点是否允许空值
3、键如果重复的话,会将键对应的值覆盖掉,返回以前旧的值,不允许重复的key,但可以有重复的value
4、计算hashcode,如果hashcode计算的结果与已有的hash值冲突了,需要再hash

评分

参与人数 1技术分 +1 收起 理由
洪建超 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马