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
HashtableHashMaptable = 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));
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
HashMapHashSetmap = new HashMap (); map.put(1, "Keys"); map.put(2, null); System.out.println(map.get(1)); System.out.println(map.get(2));
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
HashSetset = 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"); }
No comments:
Post a Comment