Adding null values to arraylist

JavaArraylist

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

It would be 1.

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

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

Solution 2 - Java

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

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick BishopView Question on Stackoverflow
Solution 1 - Javademe72View Answer on Stackoverflow
Solution 2 - JavaEranView Answer on Stackoverflow
Solution 3 - Javacylinder.yView Answer on Stackoverflow