"Java" Map Talk, Hashcode (), Equals (), HashMap, TreeMap, Linkedhashmap, Concurrenthashmap

Source: Internet
Author: User

Excellent articles for reference:

The fourth edition of Java programming ideas

"Effective Java" second Edition

The map interface is the structure of the map table , maintaining the corresponding relationship between the key object and the value object, called the key-value pair .

> Hashcode () and Equals ()

Hashcode () and Equals () are the identities used to identify objects.

In a hashmap or similar implementation, looking for an object that is mapped to a range of subscripts through the hash value returned by Hashcode (), compares the linked list of this subscript by equals () for the existence of the same object.

Simply put,hashcode () is used for reference, fast positioning (reduced range), and really equals equals ().

Default hashcode () and equals ()

How the object does not overwrite These two methods is inherited by the object.

In object , Hashcode () computes the hash value using the object's address , and equals () compares the address of the object only.

When necessary, we need to cover both methods.

What are the principles of covering these two methods?

The coverage of Equals () is primarily based on the business of this object.

The overriding principle of hashcode () can be found in the sectioneffective Java, "overriding equals When overriding Hashcode".

There are several more important principles:

1, two equal equals objects whose hashcode are equal.

2, two equals equal to the object, its hashcode may be equivalent.

3, The good hashcode () should produce the distributed uniform hash code.

Based on the 3rd,"effective Java" has specific recommendations.

1, the definition of the variable result is nonzero.

2. Use the formula result = * result + C, where C is the hash value of each field in the class.

The Hashcode () generated with Eclipse is similar to this principle, and we can look at:

 Public classUser {PrivateInteger ID; PrivateString name; Private BooleanFlag =false; Private LongPhoneNumber; @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result + (flag 1231:1237); Result= Prime * result + ((id = =NULL) ? 0: Id.hashcode ()); Result= Prime * result + ((name = =NULL) ? 0: Name.hashcode ()); Result= Prime * result + (int) (phonenumber ^ (PhoneNumber >>> 32)); returnresult; } @Override Public Booleanequals (Object obj) {if( This==obj)return true; if(obj = =NULL)            return false; if(GetClass ()! =Obj.getclass ())return false; User Other=(User) obj; if(Flag! =Other.flag)return false; if(id = =NULL) {            if(Other.id! =NULL)                return false; } Else if(!id.equals (other.id))return false; if(Name = =NULL) {            if(Other.name! =NULL)                return false; } Else if(!name.equals (other.name))return false; if(PhoneNumber! =other.phonenumber)return false; return true; }            }
View Code

> Common Map implementations

The map interface has several common implementation classes, HASHMAP, TreeMap, Linkedhashmap, and Concurrenthashmap. One of the most commonly used hashmap.

HashMap, based on a hash table, finds fast (dependent on hashcode () and Equals ()) and stores elements unordered.

TreeMap, based on red and black trees, is stored in order (dependent on compareable).

Linkedhashmap, based on the hash list, two-way linked list implementation. such as HashMap's lookup speed, the traversal is orderly (the default is the insertion order, you can set by the construction method "least recently Used (Least recently used) Order").

concurrenthashmap, Thread-safe hashmap, is used to replace the hashtable (thread-safe, but based on the entire object of the lock implementation, efficiency is not high), and Concurrenthashmap is the use of segmented locking method, Increased efficiency.

The code demonstrates two sorts of Linkedhashmap:

ImportJava.util.LinkedHashMap;ImportJava.util.Map; Public classLinkedhashmaptester { Public Static voidMain (string[] args) {System.out.println ("Linkedhashmap is arranged according to the insertion Order:"); Map<string, string> map =NewLinkedhashmap<string, string>();  for(Integer i = 0; i < 5; i++) {Map.put ("K" + i.tostring (), "V" +i.tostring ()); }                 for(Integer i = ten; i > 5; i--) {Map.put ("K" + i.tostring (), "V" +i.tostring ());        } System.out.println (map); Map.get ("K10");                SYSTEM.OUT.PRINTLN (map); System.out.println ("The Linkedhashmap is arranged according to the least recently used (Least recently used) Order:"); Map=NewLinkedhashmap<string, string> (0.75f,true);//There are no other constructor methods to set its sort to true. The initial capacity, load factor uses the default of 16 and 0.75.          for(Integer i = 0; i < 5; i++) {Map.put ("K" + i.tostring (), "V" +i.tostring ()); }                 for(Integer i = ten; i > 5; i--) {Map.put ("K" + i.tostring (), "V" +i.tostring ());        } System.out.println (map); Map.get ("K10");    SYSTEM.OUT.PRINTLN (map); }}
View Code

Log, note the location of "K10" after using "K10":

Linkedhashmap are arranged according to the insertion order: {k0=v0, K1=v1, K2=v2, K3=v3, K4=v4, K10=V10, K9=v9, K8=v8, K7=v7, k6=v6}{k0=v0, K1=v1, K2=v2, K3=v3, K4=v4, K10=V10, K9=v9, K8=v8, K7=v7, k6=V6}linkedhashmap in the order of least recently used (Least recently used): {k0
    =v0, K1=v1, K2=v2, K3=v3, K4=v4, K10=V10, K9=v9, K8=v8, K7=v7, k6=v6}{k0=v0, K1=v1, K2=v2, K3=v3, K4=v4, k9=v9 , K8=v8, K7=v7, K6=v6, K10=V10}
View Code

"Java" Map Talk, Hashcode (), Equals (), HashMap, TreeMap, Linkedhashmap, Concurrenthashmap

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.