Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

java - Two ways to check if a list is empty - differences?

I have a short question.

Lets assume we have a List which is an ArrayList called list. We want to check if the list is empty.

What is the difference (if there is any) between:

if (list == null) { do something }

and

if (list.isEmpty()) { do something }

I'm working on an ancient code (written around 2007 by someone else) and it is using the list == null construction. But why use this construction when we have list.isEmpty() method...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The first tells you whether the list variable has been assigned a List instance or not.

The second tells you if the List referenced by the list variable is empty. If list is null, the second line will throw a NullPointerException.

If you want to so something only when the list is empty, it is safer to write :

if (list != null && list.isEmpty()) { do something }

If you want to do something if the list is either null or empty, you can write :

if (list == null || list.isEmpty()) { do something }

If you want to do something if the list is not empty, you can write :

if (list != null && !list.isEmpty()) { do something }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...