Java 向数组列表添加空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27107072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:49:53  来源:igfitidea点击:

Adding null values to arraylist

javaarraylist

提问by Nick Bishop

Can I add nullvalues to an ArrayListeven if it has a generic type parameter?

即使它具有泛型类型参数,我也可以向其添加nullArrayList吗?

Eg.

例如。

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

If so, will

如果是这样,将

itemsList.size();

return 1 or 0?

返回 1 还是 0?

If I can add nullvalues to an ArrayList, can I loop through only the indexes that contain items like this?

如果我可以将null值添加到ArrayList,我是否可以只遍历包含此类项目的索引?

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

Or would the for each loop also loop through the null values in the list?

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

采纳答案by deme72

Yes, you can always use nullinstead of an object. Just be careful because some methods might throw error.

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

It would be 1.

它将是 1。

also nulls would be factored in in the for loop, but you could use

nulls就在for循环中被分解,但你可以使用

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

回答by Eran

You can add nulls to the ArrayList, and you will have to check for nulls in the loop:

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

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

   }
}

itemsList.size();would take the nullinto account.

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);
 }

Output :

输出 :

2
null value
5

回答by cylinder.y

You could create Util class:

您可以创建 Util 类:

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

        return list.add(element);
    }
}

And then use it:

然后使用它:

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