Recently, I've been doing only source reviews, but since there were a lot of children who are doing their best to check the null / empty list, I thought, "Maybe I don't know it?", So I summarized it.
The "work hard check" that I often pointed out in recent reviews looks like this: arrow_down:
Work hard
List<String> strList = new ArrayList<String>();
//Assuming strList is defined somewhere or comes in as a method argument ...
if (strList == null || strList.size() == 0) {
return true;
}
Yeah, it's right. If you can check null & size, you can avoid nullPointerException which is boring for the time being. For new employee training from April to June, if you can write this way, you will pass: white_flower:
Java has a lot of useful external libraries (mostly programming languages, not just Java). The famous doco is "org.apache.commons". This time I will write smartly using org.apache.commons.
Smart processing
import org.apache.commons.collections4.*
List<String> strList = new ArrayList<String>();
//Assuming strList is defined somewhere or comes in as a method argument ...
if (CollectionUtils.isEmpty(strList)) {
return true;
}
Notable is in the if statement: exclamation: I used "Apache Commons Collections" which is one of the external libraries.
Apache Commons Collections is a library that handles Java collections conveniently, and there is `CollectionUtils.isEmpty ()`
that handles null check and size 0 check together!
Since it is an external file, it cannot be used just by installing Java normally: cry: You need to download and load it.
In eclipse, if ```org.apache.commons.collections4. * `` `appears in the import candidates when input completion of CollectionUtils, it can be judged that it has been read. However, it is mostly introduced in most Java projects, maybe.
Null / empty check of List can be written neatly by using `CollectionUtils.isEmpty ()`
: pencil2:
However, it must be pre-loaded with Apache Commons Collections.
Recommended Posts