首页 > 代码库 > HashMap与Hashtable的区别
HashMap与Hashtable的区别
两者的区别主要集中以下几个方面:
1.key是否允许为空
HashMap允许key为null,Hashtable不允许key为null。
2.value是否允许为空
HashMap允许value为空,Hashtbale不允许value为null。
3.线程是否安全
HashMap线程不安全,Hashtable线程安全。
4.Hashtable部分源码:
//使用了同步机制,线程安全 public synchronized V put(K key, V value) { // Make sure the value is not null if (value =http://www.mamicode.com/= null) {//value不允许为null throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry<?,?> tab[] = table; int hash = key.hashCode();//key不能为null int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry<K,V> entry = (Entry<K,V>)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; }
HashMap与Hashtable的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。