I know it is a primitive question but I want to learn the smartest way.
I want to loop over the ArrayList<Integer> intList and it can be null. I have 2 ways of doing it
if(intList != null) {
for(int i = 0; i < intList.size(); i++){
System.out.println(intList.get(i));
}
}
and
for (int i = 0; intList != null && i < intList.size(); i++){
System.out.println(intList.get(i));
}
First way seems more pretty to me. What do you think? What are your implementations in that situation?
Excuse me, if it is duplicate question but I can’t find one
Thanks
In this case I would choose the first implementation as well because its intent is clearer.
Generally, I would try to avoid a
List(or any otherCollectionobject, really) beingnull. When evaluating aList(which is suddenly and unexpectedlynull) you most probably want to abort before any processing takes place so either case of looping over the collection would not occur.