一、 List、HashMap和HashTable的关系与区别
List是接口,特性是按顺序,可以重复 HashMap,实现了map接口,是键值对(key-value)HashTable ,实现了map接口。继承于dictionary,他与HashMap的区别可以从下面的引用总结为一下几点:
HashTable是同步支持多线程的。HashMap不支持,但是Jdk1.5之后,ConcurrentHashMap支持了。HashTable不允许null键和值,HashMap允许HashMap是HashTable轻量级的实现
下图可以很清楚的说明List和HashMap的关系
HashMap和HashTable我引用了下面一段话
HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的分别。主要的区别有:线程安全性,同步(synchronization),以及速度。
HashMap是非synchronized,而Hashtable是synchronized,这意味着Hashtable是线程安全的,多个线程可以共享一个Hashtable;而如果没有正确的同步的话,多个线程是不能共享HashMap的。Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的扩展性更好。
另一个区别是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。所以当有其它线程改变了HashMap的结构(增加或者移除元素),将会抛出ConcurrentModificationException,但迭代器本身的remove()方法移除元素则不会抛出ConcurrentModificationException异常。但这并不是一个一定发生的行为,要看JVM。这条同样也是Enumeration和Iterator的区别。
由于Hashtable是线程安全的也是synchronized,所以在单线程环境下它比HashMap要慢。如果你不需要同步,只需要单一线程,那么使用HashMap性能要好过Hashtable。
HashMap不能保证随着时间的推移Map中的元素次序是不变的。
hashMap去掉了HashTable 的contains方法,但是加上了containsValue()和containsKey()方法
二、List、HashMap和HashTable的小例子
//ArrayList的栗子
public class CollectionTest {
public static void main(String[] args) {
Collection<String> c =new ArrayList<String>()
c
.add(
"张三")
c
.add(
"李四")
c
.add(
"王五")
System
.out.println(c)
Collection<String > d=new ArrayList<String>()
d
.add(
"赵六")
d
.add(
"冯七")
c
.addAll(d)
System
.out.println(c)
c
.addAll(c)
System
.out.println(c)
System
.out.println(
"c是否完全包含着d:"+c
.containsAll(d))
System
.out.println(
"c是否包含着赵六:"+c
.contains(
"赵六"))
//迭代器遍历
Iterator it=c
.iterator()
while(it
.hasNext()){
System
.out.print(it
.next()+
"--")
}
System
.out.println()
c
.removeAll(d)
System
.out.println(c)
c
.remove(
"李四")
System
.out.println(c)
Collection<String> f=new ArrayList<String>()
f
.add(
"王五")
c
.removeAll(f)
System
.out.println(c)
c
.clear()
System
.out.println(c)
}
}
// 输出
//HashMap和HashTable的栗子
public class HashMapTest {
public static void main(String[] args) {
Map m=new HashMap<String,String>()
m
.put(
"sky",
"blue")
m
.put(
"tree",
"green")
m
.put(
"flower",
"red")
m
.put(
"balana",
"yellow")
System
.out.println(m
.values())
System
.out.println(m
.keySet())
System
.out.println(m
.hashCode())
System
.out.println(m
.equals(m))
System
.out.println(m
.entrySet())
System
.out.println(m
.get(
"tree"))
System
.out.println(m
.remove(
"flower"))
System
.out.println(m)
//下面为hashtable,确实两个类的方法都差不多
Hashtable t=new Hashtable<String,String>()
t
.put(
"sky",
"blue")
t
.put(
"tree",
"green")
t
.put(
"flower",
"red")
t
.put(
"balana",
"yellow")
System
.out.println(t
.values())
System
.out.println(t
.keySet())
}
}
三、学习过程中,看到两篇文章特别好,做个记录
1、HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别 (面试题部分写得很好) http://www.cnblogs.com/beatIteWeNerverGiveUp/p/5709841.html 2、HashMap对HashCode碰撞的处理 http://blog.csdn.net/caisini_vc/article/details/52452498
介于现在知识广度不够和时间太少, 只是粗略看了一下,没有仔细分析。之后有时间再加深深度