Link to home
Start Free TrialLog in
Avatar of jwright9
jwright9

asked on

Is there a way to initalize a List<String> so that it is not null even if it has nothing in it?

This the declaration for my List:

private List<String> selectedItemList = new ArrayList<String>();      

for (String str :  selectedItemList) {
          System.out.println("This is my string, " + str);
}

The way this code works if selectedItemList is null the loop above throws a null pointer exception.

Is there a way to initialize selectedItemList so that it does not contain any elements yet it is no null.  I am trying to stop the exception being thrown.

Thanks,  J.
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jwright9
jwright9

ASKER

Yes you are right.  It is the only way to do it.  The way I decided to handle it is to check for null values before assigning the null or using the null value in any conditional checking.
:)

There's nothing in the code you posted that would throw NPE btw