HashTable Vs Dictionary VsHashMap
Dictionary is an abstract class, superclass of Hashtable. You should not use Dictionary as it is obsolete. As for Hashtable, the advantage it had over other maps such as HashMap was thread safety, but with the introduction of ConcurrentHashMap since Java 1.5, there is no real reason to use it any longer.
Dictionary is an abstract class in Java whereas Map is an interface. Since, Java does not support multiple inheritances, if a class extends Dictionary, it cannot extend any other class.Therefore, the Map interface was introduced.Dictionary class is obsolete and use of Map is preferred.
In summary: Don't use Dictionary
or Hashtable
, unless you really have to for compatibility reasons, use either HashMap
if you don't need thread safety, or ConcurrentHashMap
if your map is used in a concurrent environment.
Dictionary
or Hashtable
, unless you really have to for compatibility reasons, use either HashMap
if you don't need thread safety, or ConcurrentHashMap
if your map is used in a concurrent environment.
Example:
HashMap<String, String> hash_map = new HashMap<String, String>();
hash_map.put("name1", "john");
hash_map.put("name2", "marry");
System.out.println(hash_map);
System.out.println("name2= "+hash_map.get("marry"));
System.out.println("Is HashMap empty? "+hash_map.isEmpty());
hash_map.remove("name1");
System.out.println(hash_map);
System.out.println("Size of the HashMap: "+hash_map.size());
hash_map.put("name1", "john");
hash_map.put("name2", "marry");
System.out.println(hash_map);
System.out.println("name2= "+hash_map.get("marry"));
System.out.println("Is HashMap empty? "+hash_map.isEmpty());
hash_map.remove("name1");
System.out.println(hash_map);
System.out.println("Size of the HashMap: "+hash_map.size());
Output
{name1=john, name2=marry}
name2= marry
Is HashMap empty? false
{name2=marry}
Size of the HashMap: 1
{name1=john, name2=marry}
name2= marry
Is HashMap empty? false
{name2=marry}
Size of the HashMap: 1
No comments:
Post a Comment