1、Hashtable
Hashtable是一种基本的数据结构,用于保存key-value pair。
(1)它不允许key和value为null的情况,如果使用一个null value,就会报NullPointerException异常;
(2)它是同步的(线程安全),即在某个时间点只有一个线程访问内部资源。
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "Lahore");
cityTable.put(2, "Karachi");
cityTable.put(3, null); /* NullPointerEcxeption at runtime*/
System.out.println(cityTable.get(1));
System.out.println(cityTable.get(2));
System.out.println(cityTable.get(3));
2、HashMap
HashMap也是用于保存key-value pair的。
(1)它允许key和value为null;
(2)它是异步的(非线程安全),对于单线程而言,可以大大提高性能。
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);
3、HashSet
HashSet不允许重复的value。它只提供add方法而没有put方法。
如果你希望有一个唯一的非重复的list,那么HashSet是一个不错的选择。
HashSet<String> stateSet = new HashSet<String>();
stateSet.add ("CA");
stateSet.add ("WI");
stateSet.add ("NY");
if (stateSet.contains("PB")) /* if CA, it will not add but shows following message*/
System.out.println("Already found");
else
stateSet.add("PB");