Sunday, 16 December 2018

Does java.util.List.isEmpty() check if the list itself is null?




Does java.util.List.isEmpty() check if the list itself is null, or do I have to do this check myself?




For example:



List test = null;

if (!test.isEmpty()) {
for (String o : test) {
// do stuff here
}
}



Will this throw a NullPointerException because test is null?


Answer



You're trying to call the isEmpty() method on a null reference (as List test = null;
). This will surely throw a NullPointerException. You should do if(test!=null) instead (Checking for null first).



The method isEmpty() returns true, if an ArrayList object contains no elements; false otherwise (for that the List must first be instantiated that is in your case is null).



Edit:




You may want to see this question.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...