-1

I am attempting to add validation for my ArrayList if it is null, below is my current implementation:

List<Person> personList = new ArrayList<>():

if(personList!=null){

//do something

}

However, this still throws an exception If the list is deemed to be null, how can I fix this?

java123999
  • 6,974
  • 36
  • 77
  • 121

3 Answers3

2

check (personList!= null) && !personList.isEmpty() in your code.

 if((personList!= null) && !personList.isEmpty())

    //do something

 }

now it will never throw null pointer exception.

Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49
  • 2
    Please use `!personList.isEmpty()` instead of checking its size. – marstran Aug 25 '16 at 09:15
  • if `personList` would be null this would create a NullPointerException, even if it is unlikely, that you get a NullPointerException if the Arralist is created just before it, but this i not a null check – LuckAss Aug 25 '16 at 09:16
  • @LuckAss It isn't just unlikely, it is impossible. You never get null from `new ArrayList<>()`. – marstran Aug 25 '16 at 10:40
  • 1
    @marstran yeah that's right, it's just in case this is not the ful code, as it sems to be, so if he's calling some method or doing something with the arraylist before, it could be possible that it's null ;) since he wanted a check for null – LuckAss Aug 25 '16 at 10:49
0

The list is not null, since you have initialized it. It will be an emptylist in your case. You should check for personList.isEmpty()

List<Person> personList = null will return true for null check

0

This statement creates an array list, which is definitely not null.

List<Person> personList = new ArrayList<>():

So check if the list is not empty:

if(!personList.isEmpty()) 

or

if(personList.size() != 0)
Tom
  • 16,842
  • 17
  • 45
  • 54
Vishnu P N
  • 415
  • 5
  • 19