AbstractCollection中的contains()方法

时间:2014-10-14 09:37:09

标签: java collections contains

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?谢谢。

1 个答案:

答案 0 :(得分:6)

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

it.next().equals(o)

将抛出NullPointerException