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

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

我错过了什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值