Hashes in Java are robust. They all seems to be similar however there are some differences we should pay close attention to them before selecting one to use in the design. Below is the list of these Hashes with specific features on how they different from each other:
Map
. it is an interface
. An object that maps keys to values
. A map cannot contain duplicate keys; each key can map to at most one value.
. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
.example
[java]
Map<String, Integer> m = new HashMap<String, Integer>();
[/java]
HashMap
. not an interface
. it is unsynchronized. So come up with better performance
. Permits nulls
. allows null values as key and value
. does not guarantee that the order of the map will remain constant over time.
.example
[java]
HashMap<Integer,String> productMap = new HashMap<Integer,String>();
productMap.put(1, "Keys");
productMap.put(2, null);
[/java]
HashTable
. doesn’t allows null values as key and value. You will get NullPointerException if you add null value.
. is synchronized. So it comes with its cost. Only one thread can access in one time
.example:
[java]
Hashtable<Integer,String>; cityTable = new Hashtable<Integer,String>();
cityTable.put(1, "New York");
cityTable.put(2, "San Franscisco");
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));
[/java]
HashSet
. does not allow duplicate values.
. It provides add method rather put method.
. it can be used where you want to maintain a unique list.
. example
[java]
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");
[/java]
put your comments/feedback in the comment box.
I really like it when folks arrive with each other and share opinions, fantastic web site, maintain it up.
ReplyDelete