JDK1.9 集合框架源码阅读——Map系列——有趣的问题及源码解答

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中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值