A ing table is a data structure used to store key-value pairs. If a key is provided, the value can be queried.
Map interface method:
| Modifier and type |
Method and description |
void |
clear()
Removes all of the mappings from this map (optional operation ). |
boolean |
containsKey(Object key)
ReturnsTrueIf this map contains a mapping for the specified key. |
boolean |
containsValue(Object value)
ReturnsTrueIf this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> |
entrySet()
ReturnsSetView
Of the mappings contained in this map. |
boolean |
equals(Object o)
Compares the specified object with this map for equality. |
V |
get(Object key)
Returns the value to which the specified key is mapped, ornullIf this map contains no mapping for the key. |
int |
hashCode()
Returns the hash code value for this map. |
boolean |
isEmpty()
ReturnsTrueIf this map contains no key-value mappings. |
Set<K> |
keySet()
ReturnsSetView
Of the keys contained in this map. |
V |
put(K key, V value)
Associates the specified value with the specified key in this map (optional operation ). |
void |
putAll(Map<?
extends K,? extends V> m)
Copies all of the mappings from the specified map to this map (optional operation ). |
V |
remove(Object key)
Removes the mapping for a key from this map if it is present (optional operation ). |
int |
size()
Returns the number of key-value mappings in this map. |
Collection<V> |
values()
ReturnsCollectionView
Of the values contained in this map. |
The Java class library provides two common implementations for ing tables: hashmap (hash key columns) and treemap (sort elements in the overall order of keys and organize them into search trees ), both classes implement the map interface.
Hashmap is faster than treemap, but does not have the sorting function. The following focuses on hashmap:
Hashmap
Both hashmap and hashset are data structures such as hash.
Hash table)
A hash is implemented by a linked list array. Each list is a bucket, and a bucket is a linked list. As shown in, the graph has 16 buckets. Obtain the position of the element based on the keyword hashcode and the total number of buckets. In the figure, 0 ~ 15 indicates the bucket label, and some numbers on the right represent the hash code of the keyword. In the following hash, four spaces are used, that is, 36% of the space is used. By default, the load factor of the hash table is 0.75. That is, when the space of the hash table is used, the rehashed is used, and the total number of buckets is doubled. NOTE: If not set, the initial default value of the total number of buckets is 16.
Here we mainly discuss hashmap:
The hashmap table only obtains the linked list on which the element is stored Based on the hashcode of the keyword, determining whether two objects are equal depends on the equals method of the object. To add an object of the employee class to hashmap, you must first call the hashcode method of the key corresponding to this object (value) to calculate the hash code of the key, then the index of the bucket with the remaining key value is obtained from the total number of buckets. If the returned hash code is the same as the hash code of a key already exists in hashmap, the second value replaces the first value. The key must be unique and cannot store two values for the same key. That is to say, in the hash ing table, the value is completely a subsidiary of the key and does not affect the storage at all.
Hashmap is stored in the bucket as an entry reference. A bucket is actually an entry linked list. An entry is a data structure that contains instance domains such as key, value, and next. Next indicates the location of the next reference. If next = NULL, the entry chain is over. When performing the add operation, hashmap always adds the latest element to the header of the entry linked list in the bucket, and then points the next of the latest element to the old linked list, therefore, the earliest elements must be at the end of the linked list.
Other knowledge must read this article: hashmap in Java
Add an ocjp question to enhance understanding:
Given
public class Person { private name; public Person(String name) { this.name = name; } public int hashCode() { return 420; } }
Which statement is true?
A. the time to find the value from hashmap with a person key depends on
Size of the map.
B. Deleting a person key from a hashmap will delete all MAP entries for all keys of type person.
C. inserting a second person object into a hashset will cause the first person object to be
Removed as a duplicate.
D. The time to determine whether a person object is contained in a hashset is constant and does not
Depend on the size of the map.
Answer:
The following is an explanation:
Red for translation
Option B: deleting the key corresponding to a person object in hashmap will delete all entries of the person class in the hash ing table. Error: the key value of the person object in hashmap is not determined by the person object, but the key given by the program, such as staff. add ("123-345", Bob) is to add the Bob object with the key 123-456 to the hashmap named staff. Therefore, hashmap allows you to add the same object. Therefore, deleting a person object corresponding to a key does not delete all entries. Their keys are different.
C option: inserting another person object into the hashset will cause the second object to overwrite the first object. Error. Although the hashcode method of the person object returns 420, this only indicates that two person objects are in an entry linked list and the equals method is called next. Because the person class does not have the equals method, therefore, the equals method of the object is called to return the storage address of the object. Obviously, the storage addresses of the two person objects are different. In summary, different person objects can be added to a hashset, as long as the equals method returns different values.
D option: determines whether a person object exists in a hashset. The number of times is a constant and has nothing to do with the map size. Error: Because the hashcode returned by the person object is 420, the person object in the hashset is in a bucket and forms an entry linked list. The query speed is closely related to the size of the entry linked list.
A: option: the number of times the value is queried by the key depends on the map size. Correct. The larger the map, that is, the larger the number of buckets, the smaller the length of the entry chain (the smaller the chance of having the same number of hashcode and number of buckets after the remainder ).
In addition, note that hashmap has three important views:
- Set <k> keyset ();
- Collection <k> values ();
- Set <map. Entry <K, V> entryset ();
The first and third Methods return a set, while the second method returns a collection ).
The following examples use some important methods of hashmap:
Package COM. xujin; import Java. util. hashmap; import Java. util. map; import Java. util. set; public class test {public static void main (string... arg) {Map <string, employee> Staff = new hashmap <string, employee> (); employee Lily = new employee ("Lily", 4000 ); employee John = new employee ("John", 6000); staff. put ("1234-9876", Lily); staff. put ("345-8765", John); employee e = staff. get ("345-8765"); system. out. println (E. getname (); // johnsystem. out. println (staff. containskey ("1234-9876"); // truesystem. out. println (staff. containsvalue (Lily); // truesystem. out. println (staff. size (); // 2 // key set <string> mykeyset = staff. keyset (); For (string mykey: mykeyset) {system. out. println (mykey);}/* result: * 345-8765*1234-9876 * // value set (not set) // staff. the return type of values () is collection <employee> for (employee myemployee: staff. values () {system. out. println (myemployee);}/* result: * ID: 2, name: John, salary: 6000.0 * ID: 1, name: Lily, salary: 4000.0 ** // key-value pair set // staff. entryset () returns set <entry <string, employee> for (map. entry <string, employee> entry: staff. entryset () {string key = entry. getkey (); employee value = entry. getvalue (); system. out. println ("key:" + key + "\ nvalue:" + value);}/* result: * Key: 345-8765 * value: ID: 2, name: John, salary: 6000.0 * Key: 1234-9876 * value: ID: 1, name: Lily, salary: 4000.0 **/staff. remove ("345-8765"); system. out. println (staff. size (); // 1 // putall method, Map <string, Manager> otherstaff = new hashmap <string, Manager> (); manager Jim = new manager ("Jim", 6000,100 0); Manager gin = new manager ("gin", 8000,200 0); otherstaff. put ("1111-2222", Jim); otherstaff. put ("2222-3333", gin); staff. putall (otherstaff); For (map. entry <string, employee> entry: staff. entryset () {string key = entry. getkey (); employee value = entry. getvalue (); system. out. println ("key:" + key + "\ nvalue:" + value);}/* result: * Key: 1111-2222 * value: ID: 3, name: Jim, salary: 6000.0, bonus: 1000.0 * Key: 2222-3333 * value: ID: 4, name: Gin, salary: 8000.0, bonus: 2000.0 * Key: 1234-9876 * value: ID: 1, name: Lily, salary: 4000.0 **/} class employee {public employee (string name) {This. name = Name; id = nextid; nextid ++;} Public String tostring () {return "ID:" + ID + ", name:" + name + ", salary: "+ salary;} public employee (string name, double salary) {This (name); // call another constructor this. salary = salary;} // defines the accessors method public final string getname () {return name;} public double getsalary () {return salary;} public final int GETID () {return ID;} // defines the modifier method public final void setname (string name) {This. name = Name;} public final void setsalary (double salary) {This. salary = salary;} public final void raisesalary (double percent) {This. salary * = (1 + percent);} // defines the variable private string name = ""; // instance domain initialization private double salary; private int ID; private Static int nextid = 1;} class manager extends employee {Public Manager (string name, double salary, double bonus) {super (name, salary ); // super is used in the constructor. You can call the constructor setbonus (bonus);} Public String tostring () {return Super. tostring () + ", bonus:" + bonus;} public double getbonus () {return bonus;} // rewrite the getsalary method public double getsalary () {double basesalary = super. getsalary (); // call the getsalary method of the superclass return basesalary + bonus;} public void setbonus (double bonus) {This. bonus = bonus;} private double bonus ;}