Java HashMap Supplements

Source: Internet
Author: User

Java HashMap Supplements

@author Ixenos

Fragmented knowledge
    • Try to return to the interface instead of the actual type, such as returning list, Set, map instead of ArrayList, HashSet, HashMap, which makes it easy to change the data structure without changing the client-side code. This is for abstract programming

    • The Map.entryset method returns the Set view set<map.entry<k,v>>of the map map, maintaining the Entry key value pair

      • the set is supported by map mappings , so changes to the map map can be reflected in this set, and vice versa!

      • If the set is iterated while the map map is modified, the external modcount changes while the internal xxxmodcount is in its own rhythm (either through the iterator's own remove operation, or through the return of the iterator The result of the SetValue is not deterministic, except that the iterator object is not supported by map and will not be notified when the map modifies itself. Modcount exception, an exception such as nullpointexception can occur

      • the SEt support element is removed through iterator.remove,set.remove,removeall,retainall , and Clear these operations can remove the mapping from the mapping, but it does not support add or AddAll operations

Key by value
  • Many-to-one (multiple key Mapping one value): Traverse the entry of the entire map and get the required key
  •  public  static  <t, e> set<t > Getkeysbyvalue (map<t, E> Map, E value) {Set  <T> keys = new  hashset<t> ();  for  (entry<t, E> Entry: Map.entryset ()) { //  Determines whether the current entry contains value  if   (Objects.equals (value, Entry.getvalue ()) { //         The corresponding key   Keys.add (Entry.getkey ()) is obtained by entry containing the value. }}  return   keys;}  
    View Code
     Public static <t, e> set<t> getkeysbyvalue (map<t, e> Map, E value) {    return Map.entryset ()              . Stream ()               , Objects.equals (Entry.getvalue (), value)              . Map (map.entry :: GetKey)              . Collect (Collectors.toset ());}
    In Java 8:lambda
  • One-to-one (one key mapping one value):
    • The same traversal, but a direct return to the key encountered
    •  Public static <t, e> T getkeybyvalue (map<t, e> Map, E value) {    for (entry<t, e> Entry:map.entrySet ()) {        if  (objects.equals (Value, Entry.getvalue ())) {         // once found, return             return  entry.getkey ();        }    }     return NULL ;}
      View Code
    • If a large quantity is required, swap the key and value directly in the map and then GetValue.
    • You can also guava with Google's Open source framework without the Java Collection framework, where the BIMAP can be set by the value key

    • Bimap<token, character> Tokentochar =     ' [', Token.left_parenthesis, ' ('= Tokentochar.inverse (). Get (' ('= tokentochar.get (token);
      View Code

The processing of duplicate keys by put method
  • Find the key corresponding to the entry, if not empty, then add (just) Overwrite value

  •  // e is a Node<k,v> object, which is a entry  // if  (E! = null ) {//  existing mapping for key  V oldValue = E.value;  if  (!onlyifabsent | | oldValue = null  )  //  From here you can see that the corresponding entry is found and then changed the value  e.value = value;                Afternodeaccess (e);             return   OldValue; }
    put source code fragment

  • Same Hashtable also (just) overwrite value
  •  Public synchronizedv put (K key, V value) {//Make sure the value was not null        if(Value = =NULL) {            Throw NewNullPointerException (); }        //makes sure the key is not already in the Hashtable.entry<?,? > tab[] =table; inthash =Key.hashcode (); intIndex = (hash & 0x7FFFFFFF)%tab.length; @SuppressWarnings ("Unchecked") Entry<K,V> entry = (entry<k,v>) Tab[index];  for(; Entry! =NULL; Entry =entry.next) {//The hash is determined first because it is faster than equals, and the logic used is            if((Entry.hash = = hash) &&entry.key.equals (Key)) {V old=Entry.value; //you can see that the old values have been replaced.Entry.value =value; returnOld ;        }} addentry (hash, key, value, index); return NULL; }
    Hashtable's put source

Look at the data structure from Containsvalue source
  • /*** Returns <tt>true</tt> If this map maps one or more keys to the specified value. * That is, "returns true if the mapping table has one or more keys mapped to a value" *@paramvalue value whose presence in this map was to being tested *@return<tt>true</tt> If this map maps one or more keys to the * specified value*/  Public BooleanContainsvalue (Object value) {Node<K,V>[] tab;        V V; if(tab = table)! =NULL&& Size > 0) {            //iterate through each bucket (the same hash value of entry (Node) in a bucket), a bucket to hold a double-linked list             for(inti = 0; i < tab.length; ++i) {//traverse the list in the bucket and pull out all keys that map value                 for(node<k,v> e = tab[i]; E! =NULL; E = e.next) {//The successor node E.next points to the predecessor node of another hash entry key (node is a doubly linked table node)                    if((v = e.value) = = value | |(Value!=NULL&&value.equals (v))) return true; }            }        }        return false; }   
    View Code

      • For an in-depth understanding of HashMap's blog entry to skywang12345:http://www.cnblogs.com/skywang12345/p/3310835.html#a21

Java HashMap Supplements

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.