- Comparison
- Details
HashMap
Insertion order is NOT preserved and stores records based on hashcode of keys
Heterogeneous objects are allowed for both - keys & values
Only one NULL key is allowed, but as many as NULL values are allowed
Is a best choice if frequent operation is search
Constructors (Common for all Hash implemented collections)
Default (with initialCapacity as 16 and fillRatio: 0.75 i.e. new HashMap will be created when existing one is filled 75%)
int initialCapacity = Creates with predefined size = initialCapacity and fillRatio = 0.75
int initialCapacity, float fillRatio = Creates with predefined initialCapacity & fillRatio
Collections C = convert any collection to HashMap
To get synchronized version of HashMap, use
Map m = new HashMap();
Map m1 = Collections.synchronizedMap(m);
For HashMap. JVM uses ‘.equals()’ method to identify duplicate keys, hence in below program, ONLY ONE object will be stored in HashMap as key is duplicate
HashMap m = new HashMap();
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
m.put(i1, “ganesh”);
m.put(i2, “ashtakar”);
For HashMap, if GC finds a key object as null, still GC will not destroy it as it is associated with HashMap. For example, in following case, temp object will NOT be collected by GC
HashMap m = new HashMap();
Team temp = new Temp();
m.put(temp, “ganesh”);
temp = null;
SOP(m); // will print {temp=”ganesh”}
put(key, value): On put operation, hashmap calculates the hash value of the key using hashCode() method which returns a number and then calculates the bucket number using “hashcode % (n-1)”, hashCode method if overridden, MUST always return same hashcode for an object
In case there is collision i.e. two different objects has same hashcode, equals() method is used to compare KEY objects and decide whether to add new Entry or overwrite existing one
In case there is collision where two different objects results in either same or different hashcode value but same bucket number, a LinkedList is formed to store new entry with first entry having address of next entry, following info is available for each of the HashMap Entry
Key
Hashcode
Value
Next Node
Java 8 onwards, if LinkedList size grows beyond threshold i.e. 8, JVM will convert LinkedList to TreeMap (smaller keys & hashcode on left node and greater ones on right nodes), this is faster as it results in binary search which is faster
get(key): for get operation, key is again converted to hashcode and then bucket number as mentioned in #9 above, once the bucket is identified, hashcode is compared with the Entry, if it does not match (in case of LinkedList or TreeMap), the next Node Entry will be checked & so on. Once an Entry is found for hashcode, key will be compared using equals method and then Value will be returned
LinkedHasMap
Same as HashMap but insertion order is preserved
Slower than HashMap as insertion order is preserved
Hashtable
Insertion order not maintained, but based on hashcode of key
Duplicate keys not allowed, values allowed
Heterogeneous objects for keys as well as values are allowed
NULL key & values not allowed
It is synchronized, hence thread safe
Best choice for frequent search operations
Constructors (Common for all Hash implemented collections)
Default (with initialCapacity as 11 (not 16) and fillRatio: 0.75 i.e. new HashSet will be created when existing one is filled 75%)
int initialCapacity = Creates with predefined size = initialCapacity and fillRatio = 0.75
int initialCapacity, float fillRatio = Creates with predefined initialCapacity & fillRatio
Map M = convert Map to Hashtable
TreeMap
Underlying data structure is RED-BLACK tree
Insertion order is NOT preserved and it is based on some sorting order of keys
Duplicate keys are not allowed but values can be duplicated
For default natural sorting order, then keys should be comparable & homogeneous otherwise ClassCastException will be thrown
For custom comparator, then keys need NOT be homogeneous & comparable
Methods from SorteMap
firstKey(): first element in the Map
lastKey(): last element in the Map
headMap(key): elements less than or equal to ‘key’
tailMap(ele): greater than or equal to ‘key’,
subMap(key1, key2): >= key1 and <= key2
comparator(): returns null, if natural order is used
Constructors
Default (default natural sorting order of keys)
Comparator C: Customized sorting order defined by comparator object
Collections C = convert any collection to TreeMap
SortedMap S = convert SortedSet collection to TreeMap
IdentityHashMap
Same as HashMap (refer #7 in HashMap) but
For IdentityHashMap. JVM uses ‘==’ method to identify duplicate keys, hence in below program, TWO objects will be stored in IdentityHashMap as key is NOT duplicate now
HashMap m = new HashMap();
Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
m.put(i1, “ganesh”);
m.put(i2, “ashtakar”);
WeakHashMap
Same as HashMap (refer #8 in HashMap) but
GC dominates WeakHashMap i.e. For WeakHashMap, if GC finds a key object as null, GC will destroy it though it is associated with WeakHashMap. For example, in following case, temp object will be collected by GC
HashMap m = new HashMap();
Team temp = new Temp();
m.put(temp, “ganesh”);
temp = null;
SOP(m); // will print {}
ConcurrentHashMap
Implements ConcurrentMap=> Map interface
ConcurrentMap methods: putIfAbsent(key, value), remove(key, value), replace(key, oldValue, newValue)
Read operation does NOT require lock, any number of threads can perform read operations
For Write & Update operations, In normal thread entire collection is LOCKED by one thread, whereas in ConcurrentHashMap locking is at hash BUCKET LEVEL
Hence normally if there are 16 buckets, 16 threads can do read/update operations
initialCapacity & concurrencyLevel are most of the time same but need not be same e.g. initailCapacity = 16 & concurrencyLevel=8 then there will be 1 lock for 2 buckets, or initailCapacity = 16 & concurrencyLevel=32, lock for each half of the bucket
Constructors (Common for all Hash implemented collections)
Default (with initialCapacity as 16 and fillRatio: 0.75 i.e. new HashMap will be created when existing one is filled 75%)
int initialCapacity = Creates with predefined size = initialCapacity and fillRatio = 0.75
int initialCapacity, float fillRatio = Creates with predefined initialCapacity & fillRatio
int initialCapacity, float fillRatio, int concurrencyLevel = Creates with predefined initialCapacity & fillRatio & concurrencyLevel
Collections C = convert any collection to HashMap
No comments:
Post a Comment