Common methods of Mapdemo1+2 map interface and the principle of ergodic and HashMap

Source: Internet
Author: User
Tags api manual rehash set set

Common methods of MapDemo1 map interface

/** * java.util * Map interface <K,V> type parameter: K-type of the key maintained by this map V-the type definition of the map value: Map is an interface, also known as a lookup table, Java provides a set of key-value pairs (ke Y-value) forms the data structure that stores data, which becomes a map.    We can look at it as a multi-row, two-column table with a column containing key and a column of value.    Each row is equivalent to a set of key-value pairs that represent a set of data.             Note: 1.Map there is a requirement to deposit elements, that is, key cannot be duplicated, so-called key cannot be duplicated, it is not possible to have two equals result is true key.    2.Map is not strictly required for key,value types, as long as reference types are available.    Common implementation classes: map interface According to the internal structure of a number of implementation classes, which are commonly used in the internal hash table for the implementation of the HASHMAP also have the internal TreeMap 1.hashmap<k,v> (hash list, hash table, hash algorithm implementation)        2.treemap<k,v> Common methods: 1. Deposit data: V put (K key,v value) is also a method of replacing the value of the data.        Map requires key not to allow duplicates: equals of two keys in map cannot be judged to be true.        If the same key is used to replace the value operation, the Put method returns the replaced value.        If the given is not a duplicate key, the return value is null.    There is also a possibility that a key exists and the associated value value is null, and when the same key is stored, NULL is also returned.    2. Get data: V get (Object key) The function of this method is to find the corresponding value in the map according to the given key and return it, if the current map does not contain the given key, then the return value is null.        3. Detects if a given Key:boolean ContainsKey (Object key) is included to find if the map contains a given key. If the current map contains the given KEY (check to see if the inclusion is based on the equals comparison result of key.) ) 4.  Remove Data: V Remove (Object key) The function of the method is to delete the given key corresponding to the (key-value) pair. Returns the value that was deleted.*/ Public classMapDemo1 { Public Static voidMain (string[] args) {//1. Create an implementation class for the map interface HashMapMap<string,integer> Scoremap =NewHashmap<string,integer>(); /** 2. Deposit the given key-value in the map.         * NOTE: * Because the map does not allow the existence of duplicate keys, if the equals of two keys evaluates to True, * then the PUT method replaces and returns the original value value.         * The return value of the Put method is null if no same key exists. */Integer returnvalue= Scoremap.put ("Chinese", 99); /*because there is no key.equals ("language") in the map, the return value of the Put method should be null.*/System.out.println (The first experimental output statement put method return value is: "+returnvalue); /*here, output the statement, experiment, output put return value, check whether it is null. The output is null, so the return value is null when the key value of the map is not stored.*/        //join a batch of Key-value to ScoremapScoremap.put ("English", 97); Scoremap.put ("Physics", 92); Scoremap.put ("Politics", 80); System.out.println ("Scoremap table:" +Scoremap); /** Thinking? If there is a key value called "math" that originally existed, and the associated value value is NULL, * What results will the put return? * */Scoremap.put ("Math",NULL); ReturnValue= Scoremap.put ("Mathematics", 98); System.out.println (The second experimental output statement put method return value is: "+returnvalue); /*According to the above thinking, we do a test, first put "Math" key association value value is NULL * The output is also null. Proving that there is also a possible phenomenon when a key exists and the associated value value is NULL, * when the same key is stored, also returns NULL.*/        /** 3. Method of obtaining data * V get (Object key) * Gets the value corresponding to the specified key and returns NULL if the specified key does not exist in the map*/returnvalue= Scoremap.get ("language")); System.out.println ("Language achievement:" +returnvalue);//The result of Chinese language:        /*4. Check that the key "sports" is included*/        BooleanContainsport = Scoremap.containskey ("Sport"); System.out.println ("Whether it contains the result of sports:" +containsport); //Whether it contains the result of sports: false        /** 5. How to delete data*/returnvalue= Scoremap.remove ("math")); System.out.println ("The mathematical value of the deletion is:" +returnvalue); //the value of the mathematical value to delete is: 98    }}
View Code

Traversal of the MapDemo2 map

/*** Map Traversal traversal map has three ways: 1: Traverse all key:set<k> keySet () return value: Set set (because set set is unordered, cannot be duplicated, and the map key is just unordered, not REPEATABLE) 2: Traverse all Key-value Pairs: set<map.entry<k,v>> entryset () return value: The method above the set set can be interpreted as: set<entry> en   Tryset () Note: 1. The Entry (map.entry) Here is the inner class of the map, and each Entry instance represents a set of key-value in the map that provides a way to obtain key,value for 2.Entry: K GetKey ()    , the V GetValue () 3.entrySet method is to return each set of key-value pairs (that is, several entry instances) into a set set.    3: Traverse all value (relatively infrequently) collection<v> values () return value: The Collection<v> collection returns all of the value in the map after it has been stored in a collection.    Note: Because value can be duplicated, it cannot be a set set to receive.          Summary: 1. Three kinds of traversal methods, relatively complex is the 2nd. But three kinds of practicality are not high, simply taking out value value is of little significance unless it is of special use.          2. Traverse the key and Traverse entry (Key-value) pair, and note that the set set is received because it is a collection that does not repeat unordered. 3. Traverse entry note the writing format. and entry represents a set of data. */ Public classMapDemo2 { Public Static voidMain (string[] args) {//An object that defines the implementation class HASHMAP of a map interface.Map<string,integer> Scoremap =NewHashmap<string,integer>(); //add a batch of dataScoremap.put ("Language", 90); Scoremap.put ("Mathematics", 82); Scoremap.put ("Chemistry", 66); Scoremap.put ("Politics", 67); Scoremap.put ("History", 80); /** 1. Traverse all key methods set<k> KeySet () **/Set<String> Scorekeyset =Scoremap.keyset (); //Note The return value is the Set<k> collection. //Traverse Set Collection (new loop or iterator)         for(String key:scorekeyset) {System.out.println ("Traverse the key value of the Scoremap table:" +key); /*output: Traverse the key value of the Scoremap table: The key value of the political traversal Scoremap table: History traversal Scoremap table key value: Math Traversing the key value of the Scoremap table: Chemical traversal of the key value of the Scoremap table: Chinese*/        }        /** 2. Traverse all Key-value to Method set<entry> EntrySet () * Note: Entry is an instance of each Entry instance, which represents a set of data for key and value.         * When traversing, you should also pay attention to the writing format. Loop the body, using entry's own Get method, gets the value of key and value. */Set<Entry<String,Integer>> Scoreentryset =Scoremap.entryset ();  for(entry<string,integer>Entry:scoreentryset) {String subject=Entry.getkey (); Integer score=Entry.getvalue (); System.out.println ("Account:" + subject + "Score:" +score); /*output: Subjects: Political score: 67 subjects: Historical score: 80 subjects: Math score: 82 Subjects : Chemical Score: 66 subjects: Chinese score:*/        }        /** 3. Traverse all value values (not commonly used) collection<v> values () * Note: Because value can be duplicated, it cannot be a set to receive. */Collection<Integer> Valuecollect =scoremap.values ();  for(Integer value:valuecollect) {System.out.println ("Score:" +value); /*output: Score: 67 score: 80 Score: 82 Score: 66 Score:*/        }    }}
View Code

HashMap principle

HashMap is a common subclass implementation of map. In fact, the hash algorithm is used to achieve.

HashMap internally maintains a hash array (that is, an array of stored elements), which we call a hash bucket, and when we deposit a set of key-value pairs into the HashMap, HashMap first gets the return value of the Hashcode () method of the Key object. The value is then used to make a hash algorithm, which is a number that is the set of key-value pairs to be stored in the hash array in the subscript position.

When you know the subscript position, HashMap also checks to see if the current location of the hash array contains the element. (note here that each element in the hash array is not a direct store of a key-value pair, but rather a linked list in which each node in the list is actually holding the set of key-value pairs.) ) checks if the element is included, depending on whether the key currently being stored in the current hash array corresponds to the link in the list, if it does not contain the set of key-value pairs in the linked list, or replace value.

Then, when the element is fetched, HashMap also hashes the algorithm based on the hashcode value of the key, finds its position in the hash array, and then iterates through the linked list of the position, and returns the value corresponding to the key.

See here may have a question, the list should only be stored in one element, then HashMap is how to put Key-value into a linked list of a node? In fact, HashMap encapsulates each set of key-value pairs as an instance of entry and then stores the instance in a linked list.

There are nouns in the hash table that need to be understood:

    • Capacity: capacity, the number of buckets (barrels) in the hash table, that is, the hash array size.
    • Initial capacity: Initial capacity, the number of initial buckets when the hash table was created, and the default build capacity is 16. You can also use a specific capacity.
    • Size: The amount of data that is stored in the current hash table.
    • Load factor: Load factor, default value of 0.75 (that is, 75%), expansion and re-hashing (rehash) if the value of size/capacity is greater than load factor when adding data to the hash table.

Then, when the load factor is smaller than the child, the hash lookup performance increases, and the hash bucket space capacity is wasted. 0.75 is the result of a relative balance between performance and space. When creating a hash table, specify a reasonable capacity, which reduces rehash to improve performance.

/** When a class is used as a key in HashMap, its Equals method and the results of the Hashcode method directly affect the query performance of the hash table. * Reason: According to the principle of the HashMap table. See figure. * The API Manual is clear: when we rewrite the Equals method of a class, we should rewrite the Hashcode method together. * When overriding the Hashcode method, you should follow: * 1: Stability: When the value of the attribute that participates in the equals comparison has not changed, the number of calls to the Hashcode method should be the same.              * 2: Consistency: When two objects equals equal to True, the Hashcode method must return the same number, and if Hashcode is the same, the result of equals is not enforced, but is as consistent as possible. Because if the hashcode value of two objects is the same, but the equal method is false, a list is generated in the hash table, which affects the query performance*/ Public classKeyhashcode {Private intx; Private inty; @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result +x; Result= Prime * result +y; returnresult; } @Override Public Booleanequals (Object obj) {if( This==obj)return true; if(obj = =NULL)            return false; if(GetClass ()! =Obj.getclass ())return false; Keyhashcode Other=(keyhashcode) obj; if(X! =other.x)return false; if(Y! =other.y)return false; return true; }}
View Code

Common methods of Mapdemo1+2 map interface and the principle of ergodic and HashMap

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.