Map container -- HashMap and common APIs, and put, get method parsing, generation and use of hash codes, maphashmap

Source: Internet
Author: User

Map container -- HashMap and common APIs, and put, get method parsing, generation and use of hash codes, maphashmap

Map Interface

① Map is an object that stores key/value pairs. Given a key, you can query its value. The key and value are all objects;

② The key must be unique and the value can be repeated;

③ Some mappings can receive null keys and null values, while others cannot;

④ The following interfaces support ing:

Interface

Description

Map

Map unique keywords to values

Map. Entry

Description of the elements in the ing (keyword/Value Pair ). This is an internal class of Map.

SortedMap

Extended Map to maintain keywords in ascending order

⑤ Map the unique key to value through the Map interface;

6. The key is the object used for value retrieval later. Given a key and a value, you can store this value in the Map object, and then you can use the corresponding key to retrieve it;

7. Map interface definition method:

A) int size ()

B) boolean isEmpty ()

C) boolean containsKey (Object key)

D) boolean containsValue (Object value)

E) V get (Object key)

F) V put (K key, V value)

G) V remove (Object key)

H) Collection <V> values ()

I) Set <Map. Entry <K, V> entrySet () returns the set view containing the ing relationship.

 

The ⑧ Map. Entry interface represents the ing (key-Value Pair) type and is a nested Map type;

The entrySet () method defined by the ⑨ Map interface returns a Set containing the Entry ing Entry. The elements in the Set are Map. Entry types;

The method defined by the ⑩ Map. Entry interface:

A) K getKey ()

B) V getValue ()

C) V setValue (V value)

 

HashMap and common APIs

① The HashMap class is implemented based on the map interface of the hash table and allows the use of null keys and null values;

② Constructor:

A) HashMap ()

B) HashMap (Map m)

C) HashMap (int capacity)

D) HashMap (int capacity, float fillRatio)

③ HashMap implements Map and extends AbstractMap. No new method is added;

④ Hash ing does not guarantee the order of its elements. The order in which elements are added to the hash ing is not necessarily the order in which they are read by iteration;

 

Add and Output

1 Map <String, String> map = new HashMap <String, String> (); 2 map. put ("zhangsan", "Zhang San"); 3 map. put ("zhangsan", "Li Si"); // overwrites the above 'zhang san' value 4 map. put ("jay", "James"); 5 map. put ("marry", "Xiaohong"); 6 System. out. println (map );

Output result:

{Jay = James, zhangsan = Li Si, marry = Xiaohong}

 

Obtain all keys in the map

1 Set <String> keys = map. keySet (); 2 for (String key: keys) {3 System. out. println (key); 4}

Output result:

Jay

Zhangsan

Marry

 

Get all values in map

1 Collection <String> values = map. values (); 2 for (String value: values) {3 System. out. println (value); 4}

Output result:

James

Li Si

Xiaohong

 

Obtain the value corresponding to the key when getting the key

1 Set <String> keys = map. keySet (); 2 for (String key: keys) {3 System. out. println (key + "--" + map. get (key); 4}

Output result:

Jay -- James

Zhangsan-Li Si

Marry -- Xiaohong

 

1 System. out. println (map. size (); // returns the number of key-value ing relationships in this ing 2 System. out. println (map. isEmpty (); // returns true if the ing does not contain a key-value ing relationship.

Output result:

3

False

 

ReturnsSetView

1 // when we call the put (key, value) method, the key and value are first encapsulated into the static internal Class Object 2 // Entry, add the Entry object to the array. 3 // when we want to obtain all key-value pairs in map, we only need to obtain all Entry objects in the array. 4 // next, call the getKey and getValue methods in the Entry object to obtain the key-value pair 5 Set <Entry <String, String> entrys = map. entrySet (); 6 for (Entry <String, String> entry: entrys) {7 System. out. println (entry. getKey () + "----" + entry. getValue (); 8}

Output result:

Jay ---- James

Zhangsan ---- Li Si

Marry ---- Xiaohong

 

Analysis of put method steps
1/* 2 * put method step parsing 3 * HashMap call the default constructor will generate an Entry array with the underlying length of 16 4 * int hash = hash (key. hashCode ()); 5 * First, call the hashCode method of the key to obtain an integer -- hash code 6 *. Pass the hash code as a parameter to the hash function for calculation -- hash calculation -- get an integer -- hash value 7 * int I = indexFor (hash, table. length) 8 * calculate the hash value and the length of the array, and finally obtain the location where the array is stored (I) 9*10 * The HashMap internal structure is the array linked list structure 11 * because different keys may calculate the same hash value, according to the hash value, the subscript storing 12 * to the array will conflict with 13 **/

Int I = hash (zhang. hashCode ());

Int j = hash (li. hashCode ());

I may be the same as j. If both are 4, zhan-'zhangsan' is stored in location 4,

Li-'Li si' is stored in location 4.

 

Get method Parsing
1/* 2 * get method resolution 3 * When keyword search is used, multiple key-values may exist in the same hash value location, 4 * multiple key-values are stored as linked lists and compared one by one until they are found. 5 * if no null6 is returned **/7

 

Generation and use of Hash Codes

① When the hashCode () method of the object is called, the hash code value of the current object is returned. This method is supported to improve the performance of hash tables;

② Common hashCode protocols:

A) During Java application execution, the same integer must be returned when the hashCode method is called for the same object multiple times, the premise is that the information used for equals comparison of objects is not modified, and the number of executed integers from one application to the other of the same application does not need to be consistent;

B) if the two objects are equal according to the equals (Object) method, the hashCode method must generate the same integer result for each Object of the two objects;

Note: The equals (Object) method mentioned here refers to the equals method not overwritten by the subclass in the Object class;

C) if the two objects are not equal according to the equals (java. lang. Object) method, it is not required to generate different integer results to call the hashCode Method on any of the two objects. However, we should realize that generating different integer results for unequal objects can improve the performance of the hash table;

 

Create a Student class

 1 class Student{ 2     private String name; 3     private int age; 4     public Student(String name, int age) { 5         super(); 6         this.name = name; 7         this.age = age; 8     } 9     public String getName() {10         return name;11     }12     public void setName(String name) {13         this.name = name;14     }15     public int getAge() {16         return age;17     }18     public void setAge(int age) {19         this.age = age;20     }21 }

Create an object, assign values, and view elements in the main method

1 Map <Student, String> map = new HashMap <Student, String> (); 2 map. put (new Student ("zhang", 20), "zhang San"); 3 map. put (new Student ("li", 30), "li Si"); 4 map. put (new Student ("wang", 20), "wang Wu"); 5 map. put (new Student ("li", 30), "James"); 6 System. out. println (map); 7 System. out. println (map. size ());

Output result:

{Com. iotek. map. student @ 7852e922 = James, com. iotek. map. student @ 2a139a55 = James, com. iotek. map. student @ 15db9742 = Li Si, com. iotek. map. student @ 6d06d69c = Wang Wu}

4

 

Add twoNewStudent ("li", 30) same key, is considered as two

To use the hashCode method and equals method as one (generated), rewrite the hashCode method ).

 1     @Override 2     public int hashCode() { 3         final int prime = 31; 4         int result = 1; 5         result = prime * result + age; 6         result = prime * result + ((name == null) ? 0 : name.hashCode()); 7         return result; 8     } 9     @Override10     public boolean equals(Object obj) {11         if (this == obj)12             return true;13         if (obj == null)14             return false;15         if (getClass() != obj.getClass())16             return false;17         Student other = (Student) obj;18         if (age != other.age)19             return false;20         if (name == null) {21             if (other.name != null)22                 return false;23         } else if (!name.equals(other.name))24             return false;25         return true;26     }

Execute again and output the result:

{Com. iotek. map. Student @ 14e0 = James, com. iotek. map. Student @ 379830 = Wang Wu, com. iotek. map. Student @ 6e7fa19 = James}

3

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.