Hashtable
1. Retain values of key-value pair
2. Didn’t allow null for both key and value, and will get NullPointerException if add null value
3. It is synchronized, so it comes with its cost. Only one thread can access in one time
Hashtable table = new Hashtable();
table.put(1, "Beijing");
table.put(2, "Boston");
table.put(3, null); /* NullPointerException at runtime*/
System.out.println(table.get(1));
System.out.println(table.get(2));
System.out.println(table.get(3));
HashMap
1. Retain values of key-value pair
2. It allows null for both key and value
3. It is unsynchronized, so come up with better performance
HashMap map = new HashMap();
map.put(1, "Keys");
map.put(2, null);
System.out.println(map.get(1));
System.out.println(map.get(2));
HashSet
1. Retain object, doesn't store key-value pairs
2. Does not allow duplicate values, which means HashSet can be used where you want to maintain a unique objects
HashSet set = new HashSet();
set.add ("CA");
set.add ("MA");
set.add ("PA");
if (set.contains("MA")) {/* if MA, it will not add but shows following message*/
System.out.println("Already found");
} else {
set.add("NY");
}