Summary of Java Collections (ii): Map and set

Source: Internet
Author: User

Schema diagram for the collection class:

HashMap

    • Internally maintains a list of linked lists as a hash table, the default size is 16, the maximum value can be 2^30, and the default load factor is 0.75.
    • The initial size and load factor can be specified by constructing a method, and when the number of key-value pairs is greater than or equal to the critical value threshold (the current size of the array and the product of the load factor), the expansion strategy multiplies the current array size by 2.
    • Each item of the array is a linked list, and each node of the list (static inner class entry) is a key-value pair, and the hash value of the key is cached.
    • Both key and value can be null,key NULL when the node is stored in a hash table array labeled 0.

Put procedure:

     Publicv put (K key, V value) {if(Table = =empty_table)        {inflatetable (threshold); }        if(Key = =NULL)            returnPutfornullkey (value); inthash =hash (key); inti =indexfor (hash, table.length);  for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }} Modcount++;        AddEntry (hash, key, value, I); return NULL; }
    • An internal hash value is computed by the hashcode of the key, and then the hash value is used to take the remainder (the algorithm is H & (length-1), This can be reflected in the hash table length expansion strategy for the advantage of exponential mode, and then to the location of the Hashtable, and then traverse the list of the position, when encountering an equal key, replace the original value and return the original value
    • If you do not find the same record as key, add a new linked table node in the corresponding location, and then link the original link to this node, this node as the head node, when the size is greater than the threshold value, then the size of the original array is twice times larger

HashMap is not thread-safe and can cause a dead loop in a multithreaded environment (occurs when the hash table expands after transfer data) or loses data (a hash conflict occurs when a new node is added to a linked list).

HashSet
HashSet is implemented by embedding a HashMap object, which is stored by the HashMap key, and value is the same as an empty object (). Like HashMap, requires that the stored key implements the Hashcode and Equals methods, and has the same initial size and expansion strategy as the HashMap.

TreeMap

Red-Black tree: A roughly balanced two-fork lookup tree , which is roughly balanced to maintain statistical performance while maintaining a high retrieval efficiency without the need for frequent adjustments.

    • TreeMap internally uses a red-black tree to maintain its root node, each key-value embedded in one of the nodes (Entry), and Entry has left, right, parent, and color attributes to maintain its tree structure.
    • The nodes are ordered by key , which requires the key to implement the comparable interface or to pass in a comparator comparator in the construction method.
    • The iteration is sorted by key, the key will be saved with the comparison results of keys to the weight, as long as the comparison results will be considered the same copy, the key value is the first put in the key,value for the second put in the value
    • Search binary lookup tree through key get, find matches return its value, cannot find return null
    • Traversal of all node searches when acquired through value
    • TreeMap implements the SortedMap and Navigablemap interface, can be conveniently based on the order of the keys to find, such as the first, the last, a range of keys, neighboring keys and so on.
    • According to the key save, find, delete the efficiency is high, O (h), H is the height of the tree, in the case of tree balance, H is log2 (n), n is the number of nodes.
    • TreeSet
    • Internally holds a treemap, similar to hashset, without repeating elements, adding a delete to determine if the element is more efficient, O (log2n), n is the number of elements
    • Orderly, can be conveniently based on the order of the search and operation, such as the first, the last, a range of values, a value of the nearest neighbor element.

Linkedhashmap

    • Linkedhashmap is a subclass of HashMap, which has a doubly linked list that maintains the order of key-value pairs, with each key-value pair located in the hash table and also in the doubly linked list.
    • The node linkedhashmap.entry of the doubly linked list inherits from Hashmap.entry, adding before and after two reference parameters, while overriding Hashmap.entry Recordaccess and Recordremoval methods to maintain and hash tables The relationship of the middle node.
    • Linkedhashmap supports two kinds of order, one is the insertion order, the other is the order of access, by default by inserting orderly, in the construction method Accessorder set to True when in the access order, can be used to implement the LRU cache (least recently used)

Linkedhashset
Linkedhashmap also has an implementation class Linkedhashset for the corresponding set interface. Linkedhashset is a subclass of HashSet, but its inner map implementation class is Linkedhashmap, so it can also keep the insertion order

Enummap
An internal array implementation is used to construct a method that requires incoming type information. Allowed values are null, in order to differentiate between null and no value, with a static globally unique new Integer (0) value as no value

Enumset
Internally using a bit vector implementation, an abstract class that cannot be created directly from the new keyword, you must create a set of the specified enumeration type using another factory method method similar to noneof. The object that is actually created is a subclass of Enumset Regularenumset or Jumboenumset.

The specific subclass type is determined based on the number of enumerated values of the enumerated type being passed in:

    • Less than or equal to 64 returns the subclass that maintains a long variable (long is 64 bits ) as a bit vector regularenumset
    • Greater than 64 returns an internally maintained long array as a subclass of a bit vector jumboenumset

Here are some factory methods:

//The initial collection includes all enumerated values of the specified enumeration type<eextendsEnum<e>> enumset<e> AllOf (class<e>ElementType)//The initial collection includes the elements of the specified range in the enumeration values<eextendsEnum<e>> enumset<e>Range (e from, E to)//The initial collection includes the complement of the specified collection<eextendsEnum<e>> enumset<e> Complementof (enumset<e>s)//The initial collection includes all the elements in the parameter<eextendsEnum<e>> enumset<e>of (e e)<eextendsEnum<e>> enumset<e>of (e E1, e E2)<eextendsEnum<e>> enumset<e>of (e E1, e E2, E E3)<eextendsEnum<e>> enumset<e>of (e E1, e E2, E E3, e E4)<eextendsEnum<e>> enumset<e>of (e E1, e E2, E E3, E E4, e e5)<eextendsEnum<e>> enumset<e>of (e First, E ... rest)//The initial collection includes all elements in the parameter container<eextendsEnum<e>> enumset<e> copyOf (enumset<e>s)<eextendsEnum<e>> enumset<e> copyOf (collection<e> c)

Summary of Java Collections (ii): Map and set

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.