当前位置:   article > 正文

java for list null_java – 空ArrayList和带有null元素的ArrayList之...

java中new arraylist()后list中有空元素吗

我正在为一个解析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!

我错过了什么?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/823196
推荐阅读
相关标签
  

闽ICP备14008679号