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.
An ArrayList element can be an object reference or the value null . When a cell contains null , the cell is not considered to be empty. The picture shows empty cells with an "X" and cells that contain a null with null . The cells that contain null are not empty, and contribute to the size of the list.
Solution. Yes, We can insert null values to a list easily using its add() method. In case of List implementation does not support null then it will throw NullPointerException.
int[] a = new int[5]; a[0] = 1; a[2] = 'a'; a[3] = null; //Compiler complains here for (int i : a) System. out. println(i); I am assuming because its an int array and the literal value allowed is 0 and not NULL .
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With