"Null is disgusting. "-Doug Lea
"This is a mistake that I can't regret. "-Sir C. A. R. Hoare, said when evaluating his invention of null.
Careless use of nullCan cause various bugs. By studying Google code base, we found that about 95% of collections should not contain null values. For developers, it is more helpful to directly report an error to the null value of collection than to accept it silently.
Null is the correct choice.The cost of null in time and space is very low, andObject array is inevitable. However, compared with the official library, null is still one of the main causes of confusion, strange bugs, and fuzzy meanings in actual application code. In the above example, whenMap. get returnsNull, which may indicate that there is no corresponding value or that the value exists and is null. The biggest problem is that null cannot prompt what the null value means.
OptionalOptional<Integer> possible = Optional.of(5possible.get();
NotIt is exactly the same as the "option" or "maybe" structure in other languages, although there may be some similarity.
Some common class operations are listed here.
Optional
The following areStatic Method of the class:
Optional. of (T) |
Create an Optional instance that contains a given non-null reference T. If T is null, an error is reported directly. |
Optional. absent () |
Returns an absent Optional instance. |
Optional. fromNullable (T) |
Converts a reference T that may be null to an Optional instance. If T is not null, the instance is present. If T is null, the instance is absent. |
Boolean isPresent () |
If the instance contains a non-null T (present) instance, true is returned. |
T get () |
If it is present, the contained T instance is returned; otherwise. |
T or (T) |
If it is present, the contained T instance is returned; otherwise, the specified default value is returned. |
T orNull () |
If it is present, the contained T instance is returned; otherwise, null is returned. This method is the inverse process of fromNullable. |
Set <T> asSet () |
If it is present, an unchangeable singleton Set is returned. Set contains the T instance contained in Optional; otherwise, an empty immutable set is returned. |
, An error is reported directly.
EmptyToNull (String) |
IsNullOrEmpty (String) |
NullToEmpty (String) |
We want to emphasize that these methods are mainly used to deal with some annoying APIs. They are equivalent to null String and null String. And every timeYourselfThe Guava team will cry when writing code that combines null string and. (If the meanings of the two are significantly different, it would be better. However, processing them as exactly the same thing is an unfortunate and common bad taste of code .)
UsingAndAvoidingNullExplained