[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 817
  • 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

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

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