【问题标题】:contains() method in AbstractCollectionAbstractCollection 中的 contains() 方法
【发布时间】:2014-12-09 01:05:58
【问题描述】:
public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }
}

我对 AbstractCollection 中的 contains() 方法有疑问。 我认为上述实现如下:

public boolean contains(Object o) {
        Iterator<E> it = iterator();
            while (it.hasNext())
                if (it.next().equals(o))
                    return true;
        return false;
    }
}

我认为没有必要使用 null 来区分。为什么用 null 而不是 null 分隔?谢谢。

【问题讨论】:

    标签: java collections contains


    【解决方案1】:

    如果集合包含空元素,则调用 it.next() 将返回空值。所以表达式:

    it.next().equals(o)
    

    会抛出 NullPointerException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-20
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      相关资源
      最近更新 更多