Hyu*_*Lee 1 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在AbstractCollection中有一个问题contains()方法.我认为以上实现与以下相同:
public boolean contains(Object o) {
Iterator<E> it = iterator();
while (it.hasNext())
if (it.next().equals(o))
return true;
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为没有必要区分使用null.为什么分隔为null而不是null?谢谢.
如果集合包含null元素,则对it.next()的调用将返回null.所以表达式:
it.next().equals(o)
Run Code Online (Sandbox Code Playgroud)
将抛出NullPointerException