1. Preface
In actual projects, we often need to perform empty checks on various variables or objects. This is because, if no null checking is performed, a NullPointerException may occur when a null value is encountered. This is a common runtime exception that occurs when trying to access or manipulate empty object references. To avoid this exception, we need to perform careful null checks before using variables or objects to ensure that their values are valid or that they are not null values. By performing empty checks, we can better ensure the stability and reliability of the program and avoid potential errors and exceptions.
2. How to judge null
2.1 Common judgments
There are many ways to determine whether an object is null. Besides the (obj) in and ObjectUtil in hutool you mentioned, there are some other common methods. Here is a detailed description of these methods:
- (obj)This is a method provided by the Java standard library, which checks whether a given object is null. Return true if the object is not null; otherwise return false.
-
ObjectUtil in hutoolHutool is a Java toolkit that provides many practical tools and methods. There is also a method in the ObjectUtil class to determine whether the object is null. Using Hutool's ObjectUtil, you can check if an object is null like this:
(obj)
- null != objThis is a traditional way of comparison, using the "!=" operator directly to check whether an object is null. If obj is not null, the result of the expression is false; if obj is null, the result of the expression is true.
2.2 List's judgment
A more special thing like List may not just be a non-empty judgement in a project. For List it is not equal to null and()
Not equal to 0 is two different things. Interns in the company often confuse these two situations. List does not equal null, which means that it has been initialized. There is a piece of land in the heap memory, and a size of 0 means that there has not been anything in it. For example, it does not equal null, which means that I have a bottle now, and size greater than 0 means that I have water in the bottle.
Let’s take a look at the source code:
public boolean isEmpty(List list) { if (list != null && () > 0) { return false; } else { return true; } }
It is equivalent to judging whether there is water in the bottle (provided that the bottle already exists. If the bottle does not exist, it will be thrown out.NullPointerException
abnormal).
So usually it will be used togetherlist != null && > 0
To judge, or directly use the isEmpty of the CollUtil tool in HuTool. There are Set, Map, etc.
2.3 String's judgment
Here we still use the concept of bottle and water. When String is null, equals(String) or length() is called to throw it.
private void test() { String str1 = null; //Exception will be thrown here if (("")) { } //Exception will be thrown here if (() > 0) { } }
There are several ways to determine the empty string:
1. One of the methods used by most people is intuitive, convenient, but inefficient:
if(a == null || (""));
2. Compare string lengths to be efficient:
if(a == null || () == 0);
3. Java SE 6.0 has just begun to provide, and the efficiency is similar to method two:
if(a == null || ());
Of course it can also be usedtool.
(a);
- (null) = false
- (“”) = false
- (" ") = false
- (“bob”) = true
- (" bob ") = true
There is another tool classisNotEmpty()
Method, the difference between the two can be clearly seen from the comments
(a);
- (null) = false
- (“”) = false
- (" ") = true
- (“bob”) = true
- (" bob ") = true
2.4 Optional
Optional is used to preventNullpointException
of. Common methods are:
-
.empty()
:Create an empty Optional instance -
.of(T t)
:Create an Optional instance and report an exception to null time -
.ofNullable(T t)
:If t is not null, create an Optional instance, otherwise create an empty instance -
isPresent()
:Determine whether there is a value in the container -
ifPresent(Consume lambda)
:If the container is not empty, execute the Lambda expression in brackets. -
orElse(T t)
:Get the element in the container. If the container is empty, return the default value in parentheses. -
orElseGet(Supplier s)
:If the call object contains a value, return the value, otherwise return the value obtained by s -
orElseThrow()
:If empty, the defined exception is thrown, and if it is not empty, it returns the current object -
map(Function f)
:If there is a value to process it and return the processed Optional, otherwise return()
-
flatMap(Function mapper)
:Similar to map, the return value must be Optional -
T get()
:Get elements in the container, if the container is empty, throw itNoSuchElement
abnormal
Let’s take a look at a common example:
There is a Boolean property in the baseInfo class, which returns false if empty, and does not take its value for empty, and requires four lines.
boolean blind = false; if (null != ()) { blind = (); }
When using Optional, one line is done, very elegant.
boolean blind = (()).orElse(false);
Optional in Java is a container object that can be null. If the value exists, the isPresent() method returns true. Calling the get() method will return the object.
There are three ways to create Optional objects:
- Create an empty Optional object: ().
- Create an Optional object with a non-null value: (T value).
- Create an Optional object with any value: (T value).
The use scenario of Optional objects is mainly to deal with null pointer exceptions, which is equivalent to a container. When storing objects in it, if the object is empty (null), Optional will return an empty Optional instance, otherwise it will return a non-empty Optional instance.
Here is an example of using an Optional object:
Optional<String> optional = ("test"); (); // true (); // "test" ("fallback"); // "test" ((s) -> ((0))); // "t"
In the above code, an Optional object containing the string "test" is first created. Then use the isPresent() method to check whether the value is null, and use the get() method to get the value. Next, use the ifPresent() method to check whether the value exists. If it exists, execute the code in the lambda expression. In this example, the output is "t".
To sum up, Optional objects in Java can be used to avoid null pointer exceptions, which provide a more elegant and concise way to handle possible null values.
3. Summary
Each method has its own applicable scenarios, and chain programming is no exception. While it can make the code more elegant, it may reduce logic and readability. Therefore, when using it in a project, it needs to be carefully considered according to the specific circumstances.
This is the article about how Java gracefully determines whether an object is empty. For more relevant Java content to determine whether an object is empty, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!