【问题标题】:Adding null values to arraylist将空值添加到数组列表
【发布时间】:2015-01-22 07:07:55
【问题描述】:

即使 ArrayList 具有泛型类型参数,我是否可以将 null 值添加到它?

例如。

ArrayList<Item> itemList = new ArrayList<Item>();
itemList.add(null);

如果有,会

itemsList.size();

返回 1 还是 0?

如果我可以将null 值添加到ArrayList,我可以只循环包含此类项目的索引吗?

for(Item i : itemList) {
   //code here
}

或者 for each 循环是否也会遍历列表中的空值?

【问题讨论】:

标签: java arraylist


【解决方案1】:

是的,您始终可以使用null 代替对象。请小心,因为某些方法可能会引发错误。

应该是 1。

nulls 也将被考虑到 for 循环中,但您可以使用

for (Item i : itemList) {
    if (i != null) {
       //code here
    }
}

【讨论】:

  • 例如,如果提供的值为 null,List.of(...) 将抛出。这很愚蠢——只是把它放在那里。在列表中有一个空值是完全合法的!
【解决方案2】:

您可以向ArrayList 添加空值,并且必须在循环中检查空值:

for(Item i : itemList) {
   if (i != null) {

   }
}

itemsList.size(); 会考虑null

 List<Integer> list = new ArrayList<Integer>();
 list.add(null);
 list.add (5);
 System.out.println (list.size());
 for (Integer value : list) {
   if (value == null)
       System.out.println ("null value");
   else 
       System.out.println (value);
 }

输出:

2
null value
5

【讨论】:

  • 谢谢,我猜 .size() 方法也会考虑空值。
【解决方案3】:

你可以创建 Util 类:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

然后使用它:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

【讨论】:

  • 如果列表一开始就为空,这将永远不会向列表中添加任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 2023-04-02
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多