课程: https://www.imooc.com/video/21569
Map初识
Map接口及其实现类
Map接口通用方法
V put(K key, V value) # 存入一个key-value项
V get(K key) # 根据key值返回value值
V remove(Object key) # 根据key值删除Map中的一个key-value项
boolean containsKey(Object key) # 是否包含指定的key
HashMap的使用
HashMap的构造方法
HashMap() # 使用默认初始容量(16)和默认加载因子(0.75)构造一个空HashMap
HashMap(int initialCapacity) # 使用指定的初始容量和默认加载因子(0.75)构造一个空HashMap
HashMap(int initialCapacity, float loadFactor) # 使用指定初始容量和指定加载因子构造一个HashMap
HashMap的基本用法
// use the default initial capacity(16) and default loadFactor(0.75)
Map<String, Object> userMap = new HashMap<String, Object>();
// put an item(key-value) into the map
userMap.put("zs", new Integer(120));
// get an value from assigned key
userMap.get("zs")
public class GeneralUsageInMap {
public static void main(String[] args) {
// use the default initial capacity(16) and default loadFactor(0.75)
Map<String, Integer> userMap = new HashMap<String, Integer>();
userMap.put("zs01", 120);
userMap.put("zs02", 120);
userMap.put("zs03", 120);
userMap.put("zs04", 120);
userMap.put("zs05", 111);
Integer num02 = userMap.get("zs03");
Integer num01 = userMap.get("zs05");
System.out.println("num02: " + num02); // num02: 120
System.out.println("num01: " + num01); // num01: 111
}
}
HashMap的Entry结构
Entry底层实现
static class Entry<K, V> implements Map.Entry<K, V>{
final K key;
V value;
Entry<K, V> next;
final int hash;
}
使用案例
public class GeneralUsageInMap {
public static void main(String[] args) {
// use the default initial capacity(16) and default loadFactor(0.75)
Map<String, Integer> userMap = new HashMap<String, Integer>();
userMap.put("zhang1", 2);
userMap.put("zhang2", 4);
userMap.put("zhang3", 3);
userMap.put("zhang4", 1);
userMap.put("zhang5", 5);
// output the grades of "zhang2"
int zhang2Grade = userMap.get("zhang2");
System.out.println("zhang2's grade: " + zhang2Grade); // zhang2's grade: 4
// default output the map
System.out.println(userMap); // {zhang2=4, zhang3=3, zhang1=2, zhang4=1, zhang5=5}
// output the content of the map according to the hash and address of each item of the map
}
}
利用map.keySet()遍历HashMap
private static void outputMapWithKeySet(Map<String, Integer> userMap) {
for(String key : userMap.keySet()) {
System.out.println("key: " + key + " - " + "value: " + userMap.get(key));
}
}
// key: zhang2 - value: 4
// key: zhang3 - value: 3
// key: zhang1 - value: 2
// key: zhang4 - value: 1
// key: zhang5 - value: 5
利用entrySet遍历HashMap
private static void outputMapWithEntrySet(Map<String, Integer> userMap) {
for(Map.Entry<String, Integer> entry: userMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - Value: " + entry.getValue());
}
}
// Key: zhang2 - Value: 4
// Key: zhang3 - Value: 3
// Key: zhang1 - Value: 2
// Key: zhang4 - Value: 1
// Key: zhang5 - Value: 5