HashMap与HashTable解读(二)
2016-03-25 11:49
183 查看
上一篇讲到了HashMap,这一篇来讲一下HashTable。
其实两者区别不是很大,HashTable出现的比较早,继承的是Dictionary,Dictionary是一个抽象类,用来存储key/value,和map实现的功能类似,不过现在这个抽象类已经过时了,被map接口所取代。
第一:
继承的类有所不同
第二:HashTable是线程安全的
看一下get方法的源码就知道了
但是正是由于HashTable是线程安全的,因为锁的存在,这也是的HashTable 的性能不如HashMap。
第三:
Key、Value均不能为null。
如果为null,就会抛出一个NullPointerException,这一点和HashMap区别还是蛮大的。
如有错误,欢迎指正
其实两者区别不是很大,HashTable出现的比较早,继承的是Dictionary,Dictionary是一个抽象类,用来存储key/value,和map实现的功能类似,不过现在这个抽象类已经过时了,被map接口所取代。
第一:
继承的类有所不同
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable
第二:HashTable是线程安全的
看一下get方法的源码就知道了
public synchronized V get(Object key) { Entry<?,?> tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return (V)e.value; } } return null; }
但是正是由于HashTable是线程安全的,因为锁的存在,这也是的HashTable 的性能不如HashMap。
第三:
Key、Value均不能为null。
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; @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; }
如果为null,就会抛出一个NullPointerException,这一点和HashMap区别还是蛮大的。
如有错误,欢迎指正
相关文章推荐
- Java DES 3DES AES Base64加密
- Linux下简单安装MongoDB
- C++学习笔记之vector类详解
- Python 正则表达式的剖析
- jQuery支持mobile的全屏水平横向翻页效果
- iOS NSString中的搜索方法rangeOfString
- 数据导入问题:[Err] [Imp] 1406 - Data too long for column 'linkman' at row 20 [Err] [Imp] INSERT INTO `excel_eprinfo`
- web压测,webbench安装测试
- Npoi操作excel
- 简单的网页处理工具-HtmlParser
- linux下 svn 操作
- JS实现的颜色实时渐变效果完整实例
- C++第一次上机实验—2
- Geo相关
- ACM1000(移动桌子)
- C++中的引用(257BinaryTreePath)
- iOS一分钟学会环形进度条
- gym 100935E (数学推导 水~)
- (java)统计小于N的数中素数的个数
- 通过archiver转换对象