This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList

 
thomas davis
Ranch Hand
Posts: 207
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List lst = new ArrayList();

do I need to check for null ? like if (lst!=null),if if I have not added values to this array list .please confirm.?

If intialize List as follows

List lst = null; or ArrayList lst =null;

In this case I need to check for null ,if I have not added values to this array list .please confirm.

If I use enhanced for loop ,od I need to check for null and size()>0 checking?

List<String> lst = new ArrayList<String>();
if( lst !=null&&(lst.size()>0)){
for(String strParam:lst){
strParam
}

}


Do I need to use the if( lst !=null&&(lst.size()>0)) as shown above for enhanced for loop?
Please explain.


What are the good practces for arraylist and enhanced for loop together?

do I need to intialize ArrayList always ?
do I need to check for null always?
do I need to check for size() always?

Thanks

 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, it's obvious



you can be sure: lst is not null

If you instead write the following statement



you can be sure: lst is null

In both cases there's no use for checks


If I use enhanced for loop ,do I need to check for null and size()>0 checking?


Try the following example and see what happens. Does it compile? Does it run without complaining?

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic