When using the Java 8 Optional
class, there are two ways in which a value can be wrapped in an optional.
String foobar = <value or null>;
Optional.of(foobar); // May throw NullPointerException
Optional.ofNullable(foobar); // Safe from NullPointerException
I understand Optional.ofNullable
is the only safe way of using Optional
, but why does Optional.of
exist at all? Why not just use Optional.ofNullable
and be on the safe side at all times?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…