If you find an error in this article, please point it out in a few minutes. Thank you !!
This article mainly summarizes the usage of the map interface and its important implementation classes.
Iii. Map Interface
Every member method in map consists of a key and a value. The map interface does not directly inherit from the collection interface because it encapsulates a set of key-value objects of a pair, duplicate keys cannot appear in the set of map interfaces, because each key can only correspond to one member element.
Ø the sub-interfaces and main implementation classes of the map interface include:
Sub-interfaces: bindings, concurrentmap, concurrentnavigablemap, messagecontext, logicmessagecontext, navigablemap, soapmessagemap, sortedmap
Implementation class: abstractmap, attributes, authprovider,Concurrenthashmap, Enummap,Concurrentskiplistmap,Hashmap,
Hashtable, Identityhashmap,Linkedhashmap, Printerstatereasons,Properties, Provider, renderinghints, simplebindings, tabulardatasupport,Treemap, Uidefaults,Weakhashmap
List of methods defined in the map interface:
Description of the methods defined in map:
There are not many general methods defined in the map interface.
A) add or delete an element in the map.
• Put (K, V): Put a given "key-value" pair into a given MAP
• Putall (Map <? Extends K ,? Extends V): Put the "key-value" pair in the specified map into the given map.
• Remove (Object key): removes the specified object from the set and returns the corresponding value.
• Clear (): clears all objects in the map.
B) query map-related data
• Int size (): returns the number of "key-value" pairs in this map.
• Boolean isempty (): determines whether the number of "key-value" pairs in this map is 0.
• Boolean containskey (Object key): test whether the key exists in the map.
• Boolean containsvalue (object Value): test whether the map contains the value.
• V get (Object key): queries the corresponding value in the map using the specified key.
• Collection <object value> values (): obtains all values in the map.
• Set <object key> keyset (): gets the set of keys in the current map.
• Set <entry <K, V> entryset (): gets the set of entries in the current map.
ØFeatures, implementation mechanisms, and usage of hashmap
A) features of hashmap:
Hashmap implements the map, clonemap, and serializable interfaces and inherits from the abstractmap class.
B) Implementation Mechanism of hashmap:
Hashmap is implemented based on the hash array. If the hash value of the key is the same, it is saved as a linked list. For details, see the description in hashset. I reference the term "linked list hash" on the Internet to describe such a data structure.
When a new hashmap is created, a hashmap with an empty size of 16 and a load factor of 0.75 is initialized.
/** * The table, resized as necessary. Length MUST Always be a power of two. */ transient Entry[] table;
So how is the entry implemented?
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; final int hash; ......
The code above actually tells us that the entry is a node, which holds the reference of the next element, thus forming a linked list.
In general, the underlying layer of hashmap is implemented using such a data structure.
We mentioned the use of hash, but how does the hash value establish a relationship with the storage of elements? (Hash algorithm)
In the Data Structure Course, we have learned a simple hash algorithm, that is, to give you a hash factor, through simple Remainder of the hashcode of this element, to quickly locate and index it.
The following code is available in hashmap:
/** * Returns index for hash code h. */static int indexFor(int h, int length) { return h & (length-1);}
This method is very important in hashmap. All methods related to query, add, and delete call this method. Why is the usage of such a short code so high? According to the code comment, we know that this method is based on hashcode and the length of the current table (the length of the array, not the size of MAP) to obtain the location where the element should be stored, or to index it in the table.
Now let's take a look at how hashmap handles the problem when the data volume exceeds the load factor defined in the initial definition?
In hashmap, when the data volume is large and the load limit is reached, a new hash will be made, that is, hash will be performed again. The called method is resize (), and the default input parameter of Java is 2 * Table. length. Let's take a look at the JDK source code:
/** * Rehashes the contents of this map into a new array with a * larger capacity. This method is called automatically when the * number of keys in this map reaches its threshold. * * If current capacity is MAXIMUM_CAPACITY, this method does not * resize the map, but sets threshold to Integer.MAX_VALUE. * This has the effect of preventing future calls. * * @param newCapacity the new capacity, MUST be a power of two; * must be greater than current capacity unless current * capacity is MAXIMUM_CAPACITY (in which case value * is irrelevant). */ void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity]; transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } /** * Transfers all entries from current table to newTable. */ void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do { Entry<K,V> next = e.next; int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } }
We can see that the workload of resize (rehash) is very large. Re-hash is to re-create an array of the specified capacity, and then calculate the position where each element is to be placed. This workload is indeed very large.
A very important issue arises here, that is, how to make the hash table evenly distributed, that is, how to make it not a single-chain table (limit condition, if the hash values of each key are together, will the hash space be too large (resulting in a waste of memory )?
One of the above two problems is to solve how to calculate the hash value for fast access, and the other is how to implement re-hash and when to re-hash. The premise of quick access is that the elements are evenly distributed, so that they are not concentrated to a point. The hash is that the elements are too scattered, resulting in constant table rebuilding.
In the first question, we can see such a codeReturnH & (length-1); in the second question, we said that the input value of the internal call is 2 * table. length; by default, the size of hashmap is a number of 16, except for the default structure to provide a space of 16, if we use
Public hashmap (INT initialcapacity, float loadfactor)
In the above constructor method, we will find such code:
// Find a power of 2 >= initialCapacityint capacity = 1;while (capacity < initialCapacity) capacity <<= 1;……table = new Entry[capacity];
That is to say, when we pass in 1000, it does not create a hash table with a capacity of 1000, but creates a hash table with a capacity of 1024.
In general, we find a problem, that is, in whatever case, the capacity of the hash table in hashmap is always a number of the N power of 2. There is also a formula:
When length = 2 ^ N, hashcode & (length-1) = hashcode % Length
This proves the first problem. The hash index value is actually used to calculate the remainder of the hash factor. The calculation is true only when the value is 2 to the Npower. Therefore, hashmap maintains a hash table of this size. (Bitwise operations are much faster than modulo operations)
C) How to Use hashmap:
I have used hashmap in many codes because it meets the requirements of storing associated data first, and its access speed is fast, which is a problem of choice.
The more important is the hashmap Traversal method, in my blog has specifically write hashmap Traversal method: http://blog.csdn.net/tsyj810883979/article/details/6746274
ØFeatures, implementation mechanisms, and usage of linkedhashmap
A) features of linkedhashmap:
Linkedhashmap inherits from hashmap and implements the map interface. Like hashmap, linkedhashmap allows both key and value to be null.
The hash algorithm is used in the same way as the hashmap data structure. Therefore, it cannot guarantee the ing sequence, especially the sequence persistence (and then hash ).
If you want to use multiple threads, you need to use the collections. synchronizedmap Method for external synchronization.
The difference between linkedhashmap and hashmap is that the linkedhashmap maintainer runs on the dual-link list of all entries, which can be the insertion sequence or access sequence.
B) Implementation Mechanism of linkedhashmap:
Unable to sum up, on the Internet to see such an article: http://zhangshixi.iteye.com/blog/673789
I really cannot summarize it.
ØDifferences between hashmap and hashtable:
Hashtable implements the map interface and inherits from the ancient dictionary class to implement a key-value ing table. Any non-null key-value can be put in it.
There are three main differences:
1. hashtable is implemented based on the obsolete dictionary, while hashmap is implemented based on the map interface introduced by java1.2;
2. hashtable is thread-safe, while hashmap is non-thread-safe. We can use external synchronization to solve this problem.
3. hashmap allows you to put an element whose key value is null in the list, and any number of values can be null, whereas hashtable does not allow the key or value to be null.
ØFeatures of weakhashmap:
I have never used this class. Abstract: weakhashmap is an improved hashmap that implements "weak references" to keys. If a key is no longer referenced by external entities, it can be recycled by GC. (Summary after use)
ØProperties and treemap will be summarized in the subsequent content.