Java Collection class map of source code analysis (a)

Source: Internet
Author: User

The implementation classes for the map interface in the Java collection are HashMap, Hashtable, Linkedhashmap, and TreeMap, unlike the list where map is not inherited from the collection interface . You can understand it this way:

    • Map provides a key-to-value mapping, a map cannot contain the same key, and each key can only map one value.
    • The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value sets, or a set of key-value mappings
1.HashMap
    • The basic implementation of HASHMAP is a list of linked arrays (entry<k, v>[]), that is, an array of linked lists, each element in the array is the head node of a linked list, and the underlying data type in the list is a static inner class (Node) object. These objects all have the same hash (key) value, so it is an unordered store.
1     Static classNode<k,v>ImplementsMap.entry<k,v> {2         Final intHash;3         FinalK key;4 V value;5Node<k,v>Next;6 7Node (intHash, K key, V value, node<k,v>next) {8              This. hash =Hash;9              This. Key =key;Ten              This. Value =value; One              This. Next =Next; A         } -  -          Public FinalK GetKey () {returnkey;} the          Public FinalV GetValue () {returnvalue;} -          Public FinalString toString () {returnKey + "=" +value;} -  -          Public Final inthashcode () { +             returnObjects.hashcode (key) ^Objects.hashcode (value); -         } +  A          Public Finalv SetValue (v newvalue) { atV OldValue =value; -Value =newvalue; -             returnOldValue; -         } -  -          Public Final Booleanequals (Object o) { in             if(O = = This) -                 return true; to             if(Oinstanceofmap.entry) { +map.entry<?,? > E = (map.entry<?,? >) O; -                 if(Objects.equals (Key, E.getkey ()) && the objects.equals (value, E.getvalue ())) *                     return true; $             }Panax Notoginseng             return false; -         } the}
View Code
    An instance of
    • hashmap has two parameters that affect its performance: initial capacity (default 16) and load factor (default 0.75) . Capacity is the number of buckets in the hash table, and the initial capacity is just the capacity at the time of creation of the Hashtable. hashmap is not equal to the number of objects that can be stored .

    • so When creating an instance, we need to set these two values according to our own requirements, when the space is large and the query efficiency is high, you can set the initial capacity larger, and the loading factor is smaller so the query efficiency is high, but the space utilization is not high, When the space is small and the efficiency is not very high, you can set the initial capacity smaller while the load factor setting is larger, so that the query will be slower and the space utilization will be higher.

    • According to the key keyword of the ha The length of the hash and buckets array (hash (key)%length) finds the position of the bucket, and if the hash value of the key is the same, the hash conflict (pointing to the same bucket) is each new added as the head node, and the first one added at the end of the table.

Photo from: http://blog.csdn.net/qh_java/article/details/46404439 pictures from: Http://blog.csdn.net/qh_j ava/article/details/46404439

Below through the source code to analyze, understand some basic usage of HashMap:

    • Constructors (four types)

1.HashMap (int initialcapacity, float loadfactor) The first parameter is the initial capacity, the second parameter is the load factor

2.HashMap (int initialcapacity) Only initializes the capacity, the load factor is the default value of 0.75

3. HashMap () empty constructor, load factor is default value 0.75

4.HashMap (map<? extends K,? extends v> m) initialize elements in HashMap, load factor default 0.75

    • inserting elements

1.put (K key, V value) inserts a single map element

2. Putall (map<? extends K,? extends v> m) insert a Map collection

1         // hashmap is stored by default at the hash value of key, so it is an unordered store 2         Hashmap.put ("A", +); 3         Hashmap.put ("B", +); 4         Hashmap.put ("C"); 5          for (String key:hashMap.keySet ()) {6             System.out.print (key+ ":" +hashmap.get (Key) + ","); 7         } //
View Code
    • Find element

1.get (Object key) finds corresponding value values by key value

2.containsKey (Object key) to find if the map contains the specified key

3.containsValue (Object value) to find if the map contains the specified value

1         System.out.println (Hashmap.get ("A")); //  - 2         System.out.println (Hashmap.containskey ("A")); // true 3         System.out.println (Hashmap.containsvalue (100)); // true
View Code
    • modifying elements

1.put (K key, V value) finds value with the same key value, overwriting with the new value value

1         Hashmap.put ("A", +); 2         System.out.println (Hashmap.get ("A")); //  -
View Code
    • Delete Element

1.remove (Object key) search by key to delete the corresponding Key-value

2.clear () Clears all the elements in the map

1         System.out.println (Hashmap.size ()); // 4 2         Hashmap.remove ("D"); 3         System.out.println (Hashmap.containskey ("D")); // false 4         System.out.println (Hashmap.size ()); // 3
View Code2.TreeMap
    • The basic implementation of TREEMAP is a red-black binary tree, stored in the order of two-tree according to the key value, so it is an ordered storage.

Java Collection class map of source code analysis (a)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.