Map.get(Object key)
V get(Object key);
该方法将会返回Map中对应于key的value。如果这个key不存在,则返回null。
问题
那么问题来了,如果这个map本身允许null作为value呢?这样,当该方法返回null时,就会有两种情况,一种是不存在该key,第二种是该key对应的值就是null。
解答
官方源码注释给出了解决方法:
* <p>If this map permits null values, then a return value of
* {@code null} does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
V get(Object key);
意思是说,当出现这种情况时,我们可以通过containsKey方法来区分这两种情况。
Map.entrySet()
public Set<K> keySet()
该方法返回map的所有key组成的一个集合
我们知道,该方法返回的是一个Set类型的视图,对该set的任何修改都会映射到背后的map中,反之亦然。
问题
那么问题来了,为什么对set的操作都会映射到背后的map中呢?答案在Jdk的AbstractMap.java中:
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new AbstractSet<K>() { //返回一个AbstractMap类型的set
public Iterator<K> iterator() {
return new Iterator<K>() {
//AbstractMap迭代器是对entrySet().iterator()的包装
//也就是说,当我们调用set的迭代器的remove等方法时,实际上还是
//调用的背后map的entrySet的迭代器。
private Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() {
return i.hasNext();
}
public K next() {
return i.next().getKey();
}
public void remove() {
i.remove();
}
};
}
//均是通过调用map的相应方法来实现功能的
public int size() {
return AbstractMap.this.size();
}
public boolean isEmpty() {
return AbstractMap.this.isEmpty();
}
public void clear() {
AbstractMap.this.clear();
}
public boolean contains(Object k) {
return AbstractMap.this.containsKey(k);
}
};
keySet = ks;
}
return ks;
}
我们可以看到,对set的所有操作,最终都是通过调用map的相应方法来实现的。因此,所有对set的操作都会映射到map中。