Map接口

2018-05-16  本文已影响0人  沐兮_d64c

1,Map接口

1)Map(存储的是Entry<K,V>)接口替代了Dictionaryabstract class。提供了三种视图,provides three collection views
a set of keys:不能有duplicate的key
collection of values:值的集合可以有重复值
set of key-value mappings:K-V映射的集合
2)三种内容视图

image.png
keySet():a set view of the keys contained in this map返回一个key的集合。集合通过map来支持的,当改变map会影响该set,反之亦然。The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
values():返回值的集合,当修改map会影响collection,反之亦然。The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.
entrySet():返回映射mappings的集合,改变map会影响set,反之亦然。The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
Map<String, String> map = new HashMap<>();
map.put("key1", "hzq");
map.put("key2", "pwd");
Set set = map.keySet();
set.remove("key1"); // map中移除key1的映射,set中移除key1
set.add("key3");//抛出java.lang.UnsupportedOperationException异常 

3)其他方法
int size();返回映射的个数 return the number of key-value mappings in this map
boolean isEmpty(); 如果没有key-value的映射if no key-value mappings
boolean containsKey(Object key); 判断是否包含指定key的映射mappingif contains a mapping for the specified key
boolean containsValue(Object value); 是否匹配一个或者多个key,包含指定的value。maps one or more keys to the specified value
V get(Object key); 返回指定key匹配的value,或者匹配不到返回null。the value to which the specified key is mapped, or null if this map contains no mapping for the key 当get方法返回null时,可能为null值或者匹配不到。
V put(K key, V value); 向key关联value,返回value。Associates the specified value with the specified key in this map
V remove(Object key); 移除指定映射,返回value。
boolean equals(Object o);m1.entrySet().equals(m2.entrySet())
int hashCode(); the sum of the hash codes of each entry in the map's entrySet() view

2,几个注意点

1)Map.Entry<K,V>,是一个map条目,键值对。A map entry(key-value pair)比如HashMap中的static class Node<K,V> implements Map.Entry<K,V>以及TreeMap中的static final class Entry<K,V> implements Map.Entry<K,V>

image.png
2)Map的三种内容视图,对其操作都会和map之间相互产生影响。 image.png
上一篇 下一篇

猜你喜欢

热点阅读