问题
Java 8 introduces Optional to deal with NPE. In practical application,I can‘t understand a problem.
I have the method A
public void doSomethingA(String para) {
Optional<String> name = Optional.of(para);
if (name.isPresent()) {
//do
}
}
But if para = null, it will throw NPE.
method B
public void doSomethingB(String para) {
if (para != null) {
//do
}
}
if I check para is not null, What's the difference between A and B.
Where is the meaning of Optional.
回答1:
Use Optional.ofNullable if you are unsure whether you have a value or not, but you do not want a NullPointerException
to be thrown.
Use Optional.of if you know you have a non-null-value or if it's ok for you if a NullPointerException
is thrown otherwise.
Regarding the rest of your question: why null
or Optional
you may find the following question useful: Optional vs. null. What is the purpose of Optional in Java 8?
Your question may also be related to: Why use Optional.of over Optional.ofNullable?
来源:https://stackoverflow.com/questions/43339331/optional-ofnullwill-throw-npe-i-need-to-verify-null-before-call-the-method