HashMap, WeakHashMap, LinkedHashMap in Java
Difference between HashMap and WeakHashMap
There are 4 types of references in Java: strong reference, SoftReference, WeakReference, and PhantomReference. Features of each type of links are related to the work of the Garbage Collector. If the object can only be reached using the WeakReference chain (that is, there are no strong and soft references to it), then this object will be marked for deletion.
WeakHashMap is a data structure that implements the Map interface and relies on the use of a WeakReference to store keys. Thus, the key/value pair will be removed from the WeakHashMap if the key object is no longer strongly referenced.
As an example of using such a data structure, we can cite the following situation: let's say there are objects that need to be extended with additional information, while changing the class of these objects is undesirable or impossible. In this case, we add each object to the WeakHashMap as a key, and the required information as a value. Thus, as long as there is a strong (or soft) reference to the object, you can check the hash table and extract information. Once the object is removed, the WeakReference for that key will be placed in the ReferenceQueue and then the corresponding entry for this weak reference will be removed from the WeakHashMap.
WeakHashMap uses WeakReferences. Why not create a SoftHashMap on SoftReferences?
SoftHashMap is available in third party libraries like Apache Commons.
WeakHashMap uses WeakReferences. Why not create a PhantomHashMap on PhantomReferences?
PhantomReference always returns null when the get() method is called, so it's hard to imagine the purpose of such a data structure.
LinkedHashMap - what's in it from LinkedList and what's from HashMap?
The implementation of LinkedHashMap differs from HashMap in support of a doubly linked list, which determines the order in which to iterate over the elements of the data structure. By default, list items are ordered according to their insertion order in the LinkedHashMap (insertion-order). However, the iteration order can be changed by setting the accessOrder constructor parameter to true. In this case, access is performed in the order of the last access to the element (access-order). This means that when the get() or put() methods are called, the item being accessed is moved to the end of the list.
When adding an element that is already present in the LinkedHashMap (i.e. with the same key), the order of iterating over the elements does not change.
What means "sorted" in SortedMap, except that toString() displays all the elements in order?
It also appears when iterating over a collection.
Read also:
- HashMap, Hashtable, IdentityHashMap in Java
- Queue and Deque interfaces in Java
- ArrayList and LinkedList in Java, memory usage and speed
Comments
Post a Comment