Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How Optional.ofNullable handles null pointers

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to deal with null pointers in Optional.ofNullable. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

For null detection of Integer, you can use Optional.ofNullable to construct an Optional

Then use orElse (0) to replace null with the default value and then do the + 1 operation.

For String and literal comparisons, you can put literals first

Such as "OK" .equals (s), so that even if s is null, there is no null pointer exception.

For the equals comparison of two string variables that may be null

You can use Objects.equals, which will do null processing.

For ConcurrentHashMap, since neither its Key nor Value supports null, the fix is not to save the null.

Key and Value of HashMap can be stored in null

While ConcurrentHashMap appears to be a thread-safe version of HashMap, it does not support Key and Value with null values.

This is a place prone to misunderstanding.

For cascading calls like fooService.getBarService (). Bar (). Equals ("OK")

There are many things that need to be null, including the return value of the fooService, getBarService () method, and the string returned by the bar method.

It may take several lines of code to use if-else to determine null

But with Optional, one line of code is enough.

For the List returned by rightMethod

Cannot confirm whether it is null or not

So before calling the size method to get the list size, you can also use Optional.ofNullable to wrap the return value

Then use .orElse (Collections.emptyList ()) to get an empty List when List is null, and finally call the size method.

This is the end of the article on "how to deal with null pointers in Optional.ofNullable". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report