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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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

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

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

点评

如果你的问题已经得到解决,请及时将主题改为[已解决],如果还有问题请继续追问,谢谢!  发表于 2013-3-28 08:31

评分

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

查看全部评分

3 个回复

倒序浏览
不能包含重复的键,每个键最多只能映射到一个值。
回复 使用道具 举报
不能包含重复的键,每个键最多只能映射到一个值。如果再为这个键进行赋值,那么前一个值会被覆盖,put方法也会返回前一个值。
例如:
  1. Hashtable<String,String> ht =new Hashtable<String,String>();
  2. ht.put("zhangsan","24");
  3. ht.put("zhangsan","26");
复制代码
此时Hashtable中只有一个键值对,zhangsan这个键对应的值为26,但是put("zhangsan","26")会返回被覆盖的值,即24

评分

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

查看全部评分

回复 使用道具 举报
呵呵,以前还没有注意。看了看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

查看全部评分

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