• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 824
  • Last Modified:

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.
0
jwright9
Asked:
jwright9
  • 2
1 Solution
 
CEHJCommented:
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.
You've already posted code that does exactly that
0
 
jwright9Author Commented:
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.
0
 
CEHJCommented:
:)

There's nothing in the code you posted that would throw NPE btw
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now