Null pointer
- Nullpointerexceptions are often encountered during project startup or SQL queries
- Look at the following code
- We often use them as follows
person.getCar().getName();
Copy the code
- Assuming a person doesn’t have a car, then null is definitely returned
- In engineering, it is common for us to mindlessly remove if layers to achieve a variety of specific conditions
- This approach is far less extensible and readable than you would expect in engineering code
The problem of using “if” to judge empty
- Has no meaning in itself
- The code is redundant and unreadable
- Very error-prone
The introduction of the Optional
- in
java.util.Optional<T>
Class that encapsulates the Optional value in - For example, we predict in advance that some people may not have a car, so we will put car into optional to form
Optional<Car>
- Is used when the object is empty
Optional.empty()
empty()
Method is a static factory that returns a specific single example of the Optional class
private static final Optional<? > EMPTY = new Optional<>();Copy the code
– The main difference between null references and Optional is that the Optional does not raise NullPointerException
Rewrite with Optional
class Person { private Optional<Car> car; public Optional<Car> getCar() { return car; }}Copy the code
Several ways to create
1.
- Declare an empty Optional
2.
- Create a non-null value using Optional. Of
3.
- Use the static factory method optional. ofNullable to create an Optional that can be null
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
Copy the code
- Use:
Optional<Benz> optCar = Optional.ofNullable(Benz);
Copy the code
Use Optional in stream
- Let’s say that a person has a car, the car is a Mercedes, and he wants to get the name of the Mercedes.
- So we can rewrite it as follows
- Among them
orElse
If Optional is left blank, set the default Mercedes model to large Gš
Use with filter
Read the temp value
- This implementation is not readable and is marked by if, if we add requirements
- To determine what the value of I is, we need to use if, so it’s a vicious circle, right
Use Optional+ Filter (OptionalUtility is packaged by itself)
Hope in the project more Optional less if empty š