Java's Map collection


Map collection

definition:

Store a pair of key-value objects and provide a mapping ( ) from key(key) to value(value mapping).

  • The keys are not required to be in order, but they are not allowed to be repeated.
  • The value is also not required to be ordered, but it can be repeated.

The most common Mapimplementation class is HashMapthat its storage method is a hash table, which has the advantage of high efficiency in querying specified elements.

MapThe interface provides objects that map keys to collections, and a map cannot contain duplicate keys.


HashMap

definition:

HashMapIs a hash table, it stores the key-value pair ( key- value) mapping.

Features:

  • Implements Mapthe interface, according to the key HashCodevalue storage data, has fast access speed, a maximum of one record key is null, thread synchronization is not supported.
  • It is unordered, that is, the order of insertion is not recorded.
  • Inheritance to AbstractMapachieve the Map, Cloneable, java.io.Serializableinterface.
    Insert picture description here
    Insert picture description here

实例:
// 引入 HashMap 类      
import java.util.HashMap;

public class RunoobTest {
    
    
    public static void main(String[] args) {
    
    
        // 创建 HashMap 对象 Sites
        HashMap<Integer, String> Sites = new HashMap<Integer, String>();
        // 添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        System.out.println(Sites.get(3));
    }
}
结果:
Taobao


Sorting subclass: TreeMap

Guess you like

Origin blog.csdn.net/mjh1667002013/article/details/113922199