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 Map
implementation class is HashMap
that its storage method is a hash table, which has the advantage of high efficiency in querying specified elements.
Map
The interface provides objects that map keys to collections, and a map cannot contain duplicate keys.
HashMap
definition:
HashMap
Is a hash table, it stores the key-value pair ( key
- value
) mapping.
Features:
- Implements
Map
the interface, according to the keyHashCode
value 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
AbstractMap
achieve theMap
,Cloneable
,java.io.Serializable
interface.
实例:
// 引入 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