赞
踩
我正在为一个解析JSON的REST服务编写一些验证器,我发现了一些听起来很奇怪的东西(我根本不是JAVA专家).
考虑使用两个ArrayLists:
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();
两个列表都有一些共同点:它们完全是空的(或者是空元素).但如果我这样做:
list1.add(null);
虽然两者都完全是空的,但它们的行为完全不同.并且为了使一些方法的结果非常不同:
System.out.println(list1.contains(null)); //prints true!
System.out.println(list2.contains(null)); //prints false
System.out.println(CollectionUtils.isNotEmpty(list1)); //prints true
System.out.println(CollectionUtils.isNotEmpty(list2)); //prints false
System.out.println(list1.size()); //prints 1
System.out.println(list2.size()); //prints 0
做一些研究,并查看每种方法的实现,您可以确定这些差异的原因,但仍然不明白为什么区分这些列表是有效的或有用的.
>为什么add(item)不验证item!= null?
>为什么包含(null)如果列表中充满空值则表示为false?
提前致谢!!!
编辑:
我大多同意答案,但我还没有说服所有人.这是删除方法的实现:
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If the list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* i such that
* (o==null ? get(i)==null : o.equals(get(i)))
* (if such an element exists). Returns true if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return true if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
所以,现在如果我这样做:
ArrayList list = new ArrayList();
list.add(null);
System.out.println(list.contains(null)); //prints true!
list.remove(null);
System.out.println(list.contains(null)); //prints false!
我错过了什么?
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。