简体   繁体   中英

Adding null values to arraylist

Can I add null values to an ArrayList even if it has a generic type parameter?

Eg.

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

If so, will

itemsList.size();

return 1 or 0?

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

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

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

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

It would be 1.

Also null s would be factored in in the for loop, but you could use

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

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

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

   }
}

itemsList.size(); would take the null into account.

 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

You could create Util class:

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

And then use it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM