即使具有通用类型参数,我也可以将null
值添加到ArrayList
中吗?
例如。
ArrayList<Item> itemList = new ArrayList<Item>();
itemList.add(null);
如果是这样,将
itemsList.size();
返回1还是0?
如果我可以将
null
值添加到ArrayList
,则可以仅遍历包含此类项的索引吗?for(Item i : itemList) {
//code here
}
还是for each循环还会遍历列表中的空值?
最佳答案
是的,您始终可以使用null
代替对象。请小心,因为某些方法可能会引发错误。
就是1。
在循环中也将null
包括在内,但是您可以使用
for(Item i : itemList) {
if (i!= null) {
//code here
}
}