笔试面试题目搜集整理【每日增加】
1、说说Hashtable和HashMap的区别
【答案】
(1).HashMap 类没有分类或者排序。它允许一个 null 键和多个 null 值。
(2).Hashtable 类似于 HashMap,但是不允许 null 键和 null 值。它也比 HashMap 慢,因为它是同步的,线程安全的。
(3).Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map interface的一个实现。后者为Map的骨干, 其内部已经实现了Map所需要做的大部分工作, 它的子类只需要实现它的少量方法即可具有Map的多项特性。而前者内部都为抽象方法,需要它的实现类一一作自己的实现,且该类已过时。
(4).HashMap允许将null作为一个entry的key或者value,而Hashtable不允许,还有就是,HashMap把Hashtable的contains方法去掉了,改成containsvalue(Returns true if this map maps one or more keys to the specified value)和containsKey(Returns true if this map contains a mapping for the specified key)。因为contains(Tests if some key maps into the specified value in this hashtable)方法容易让人引起误解。
(5)两者检测是否含有key时,hash算法不一致,HashMap内部需要将key的hash码重新计算一边再检测,而 Hashtable则直接利用key本身的hash码来做验证.
HashMap:
int hash = (key == null) ? 0 : hash(key.hashCode()); ----- static int hash(int h) { h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); }
Hashtable:
int hash = key.hashCode();
(6).最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap 就必须为之提供外同步。
Hashtable和HashMap采用的hash/rehash算法都大概一样,所以性能不会有很大的差异。