官网Wiki:https://github.com/google/guava/wiki
Using and avoiding null
"Null sucks." -Doug Lea
there are times when null is the right and correct thing to use. null is cheap, in terms of memory and speed, and it's unavoidable in object arrays. But in application code, as opposed to libraries, it is a major source of confusion, difficult and weird bugs, and unpleasant ambiguities -- e.g. when Map.get returns null, it can mean the value was absent, or the value was present and null.
Optional
Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."
Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
Making an Optional
Method | Description |
---|---|
Optional.of(T) |
Make an Optional containing the given non-null value, or fail fast on null. |
Optional.absent() |
Return an absent Optional of some type. |
Optional.fromNullable(T) |
Turn the given possibly-null reference into an Optional, treating non-null as present and null as absent. |
Integer i1 = null;
// 抛出异常
Optional<Integer> optionalInt = Optional.of(i1);//成功的话比非null
// 之后可以放心用
//System.out.println("optionalInt = " + optionalInt.get());
Optional<Integer> absent = Optional.absent();// 就是空引用
String s1 = "s1";
Optional<String> possible = Optional.fromNullable(s1);// 可能为空
System.out.println("possible = " + possible.get());
Query methods
String s1 = null;
Optional<String> possible = Optional.fromNullable(s1);
// 抛出异常
// System.out.println("possible = " + possible.get());
// =======query
if (optionalInt.isPresent()) {
System.out.println("true");
} else {
System.out.println("false");
}
String orDef = possible.or("default");
System.out.println(orDef);
What's the point?
Besides the increase in readability that comes from giving null a name, the biggest advantage of Optional is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case. Null makes it disturbingly easy to simply forget things, and though FindBugs helps, we don't think it addresses the issue nearly as well.
This is especially relevant when you're returning values that may or may not be "present." You (and others) are far more likely to forget that other.method(a, b) could return a null value than you're likely to forget that a could be null when you're implementing other.method. Returning Optional makes it impossible for callers to forget that case, since they have to unwrap the object themselves for their code to compile.
Ref:
https://github.com/google/guava/wiki
https://www.jianshu.com/p/97778b21bd00