Optional.of(null)will throw NPE, I need to verify null before call the method?

你离开我真会死。 提交于 2020-01-20 22:05:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!