Best practice to validate null and empty collection in Java

后端 未结 9 2007
北海茫月
北海茫月 2020-12-12 10:57

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

Currently, I am checking as below:



        
9条回答
  •  时光取名叫无心
    2020-12-12 11:30

    If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

    The code behind these methods is more or less what user @icza has written in his answer.

    Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

提交回复
热议问题