在什么情况下,map.entrySet返回的Map.Entry将为NULL

时间:2015-05-18 06:55:56

标签: java dictionary hashmap entryset

我遇到了一个代码段,它使用其条目集迭代地图,并仅执行某些操作 如果输入!= null

据我所知,即使我们没有在地图map.entrySet中输入任何内容,也会返回空集而不是null。 即使我放{null,null},那么条目将是[null=null],即具有这些元素的实例。但实例不会为空。

Map<String, String> map = new HashMap<String, String>();
        map.put(null, null);
        map.put(string1, string1);
        for(Map.Entry<String, String> entry : map.entrySet()){
            if(entry != null){
                                  //do something
            }

        }

我有以下基本问题:

  1. 在什么情况下,HashMap中的条目将为NULL?
  2. 支票是否有效
  3. 我坚信if(entry != null)过于谨慎,应该将其删除。我只是想确定一下。

4 个答案:

答案 0 :(得分:6)

迭代器可以为支持空值的集合返回空值,但正如您自己所示,Maps不可能这样做。检查是多余的,具有误导性。

答案 1 :(得分:2)

该方案无效。这是来自hashmap实现的代码

private Set<Map.Entry<K,V>> entrySet0() {
    Set<Map.Entry<K,V>> es = entrySet;
    return es != null ? es : (entrySet = new EntrySet());
}

所以,你不应该得到一个空值

答案 2 :(得分:0)

检查显然是多余的。 @Kayaman的回答很好。
但是,我不同意您的评论和@bobK的回答。

我认为您可能会混淆entry和entrySet。该检查与方法entrySet()的隐含无关。方法entrySet()仅确保entrySet不为null,而您示例中的判断是确保Set中的条目不为null。 。

Set可以包含一个空对象,因此有时我们需要进行NPE保护。我们不需要在此处进行检查的原因是Map Class确保条目集中的条目不为null。 EntrySet类中的方法forEach()是重要的方法。

    public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; (i < tab.length && modCount == mc); ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    //e is not null
                    action.accept(e);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
在此确保

e != null

答案 3 :(得分:-1)

检查可能只是检查Map是否被实例化以避免NullPointerException进一步引用该对象。
如果您认为这是为了谨慎,那么最好确保在构造函数中实例化了Map

相关问题