Java HashMap linkedhashmap Differences and principles

Source: Internet
Author: User
Tags rehash

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.

HashMap access is the return value of the Hashcode method that relies on key, and the Hashcode method is actually defined in object. It is defined as follows:
int Hashcode ()
The code is as follows:

 Public classHashmapdemo { Public Static void Main(string[] args) {map<string, integer> HashMap =NewHashmap<string,integer> (); Hashmap.put ("One",1); Hashmap.put ("both",2); Hashmap.put ("three",3); Hashmap.put ("Four",4); Hashmap.put ("Five",5); Hashmap.put ("Six",NULL);//Traverse the HashMap of key in map         for(String Str:hashMap.keySet ()) {System. out. println (str +":"+ Str.hashcode ()); }    }}

Operation Result:
six:113890
four:3149094
one:110182
two:115276
three:110339486
five:3143346

Iterate through each set of key-value pairs
Set

 Public classHashmapdemo { Public Static void Main(string[] args) {map<string, integer> HashMap =NewHashmap<string,integer> (); Hashmap.put ("One",1); Hashmap.put ("both",2); Hashmap.put ("three",3); Hashmap.put ("Four",4); Hashmap.put ("Five",5); Hashmap.put ("Six",NULL);//Traversing key-value pairsSet<entry<string, integer>>Set= Hashmap.entryset (); for(Entry<string, integer> e:Set) {System. out. Print ("key:"+e.getkey () +"\ T"); System. out. println ("Value:"+e.getvalue ()); }    }}

Operation Result:
Key:six Value:null
Key:four Value:4
Key:one value:1
Key:two Value:2
Key:three Value:3
Key:five Value:5

The Hashcode () method of overriding a class has the following considerations:
1. If a class overrides the Equals method, then the Hashcode () method should be overridden.
2. If the Equals method of two objects compares to true, then they should have the same hashcode value.
3. For the same object, multiple calls to the Hashcode () method should always return the same value if the content has not changed.
4, for two objects equals is false, does not require its hashcode value must be different, but should try to ensure that different, so as to improve the performance of the hash table.

The code is as follows:

 Public  class hashmapdemo {     Public Static void Main(string[] args) {Map<card, person> Map =NewHashmap<card, person> (); person P1 =NewPerson (NewCard ("001"),"Zhang San"); person P2 =NewPerson (NewCard ("002"),"John Doe");          Map.put (P1.getcard (), p1);          Map.put (P2.getcard (), p2); System.out.println ("Personnel information stored in the HASHMAP: \ n"+MAP);//Zhang San renamed to Zhang Shan, the identity card number is unchanged. Person P3 =NewPerson (NewCard ("001"),"Zhang Shan");          Map.put (P3.getcard (), p3); System.out.println ("Zhang San renamed to Zhang Shan after HashMap stored in the personnel information: \ n"+MAP);//Find information about 001 of people with IDSystem.out.println ("Find ID: 10001 of Personnel information:"+map.get (NewCard ("001"))); }}class Card {Private FinalString Idcard; Public Card(String Idcard) {Super();    Idcard = Idcard; } PublicStringGetidcard() {returnIdcard; }@Override     Public int hashcode() {Final intPrime = to;intresult =1; result = Prime * result + ((Idcard = =NULL) ?0: Idcard.hashcode ());returnResult }@Override     Public Boolean equals(Object obj) {//If the address is the same, then two objects are the same        if( This= = obj) {return true; }//If two objects are of the same type, compare whether their property values are the same        //If all are the same, the two objects are the same;        //Otherwise, it means that the two objects are not the same.         if(objinstanceofCard) {card = (card) obj;returnCard. Idcard. Equals ( This.        Idcard); }return false; }@Override     PublicStringtoString() {return "Card [idcard=]+ Idcard +"]"; }}class Person {PrivateCard card;PrivateString name;@Override     Public int hashcode() {Final intPrime = to;intresult =1; result = Prime * result + ((Card = =NULL) ?0: Card.hashcode ()); result = Prime * result + ((name = =NULL) ?0: Name.hashcode ());returnResult }/** * override Equals () method when two people have the same ID number and the same name, it means that the two are the same person. */      @Override     Public Boolean equals(Object obj) {if(obj = = This) {return true; }if(objinstanceofperson) {Person P = (person) obj;return  This. Card.equals (P.card) && This. Name.equals (P.name); }return false; } Public  Person(Card, String name) {Super(); This. card = Card; This. name = name; } PublicCardGetcard() {returnCard } Public void Setcard(card) { This. card = Card; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }@Override     PublicStringtoString() {return "person [name="+ name +"]"; }}

Operation Result:
Information about the people stored in the HASHMAP:
{Card [Idcard=001]=person [Name= Zhang San], card [Idcard=002]=person [name= John Doe]}
Zhang San renamed to Zhang Shan after the HashMap stored in the personnel information:
{Card [Idcard=001]=person [Name= Zhang Shan], card [Idcard=002]=person [name= John Doe]}
Find ID: 10001 people information: person [name= Zhang Shan]

Loading factor and HashMap optimization

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.
For example:

Map<StringIntegermapnew HashMap<StringInteger>(10000);

This method can be used when storing large amounts of data, reducing the number of expansions and improving performance
If the amount of data is small, it is not recommended to use this method, resulting in wasted space, with the default non-parametric

Linkedhashmap to achieve an orderly map

The hash table and linked list implementations of the Map interface have a predictable sequence of iterations. The difference between this implementation and HASHMAP is that Linkedhashmap maintains a two-way loop linked list. This list defines the order of the iterations, which is usually the order in which the elements will be held.
It is important to note that if you re-deposit the key in the map, the position of the key will not change, just replace the value.

Summarize:
The difference between HashMap and Linkedhashmap is that HashMap is unordered, linkedhashmap is orderly. When using HashMap, we should choose the best solution according to the actual situation, and reduce the waste of performance and space.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java HashMap linkedhashmap Differences and principles

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.