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 to solve the problem that Map collection uses get method to return null and throw null pointer exception

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces how to solve the problem of Map collection using get method to return null to throw null pointer exception, the article is very detailed, has a certain reference value, interested friends must read it!

Preface

1.Map can only store objects, not basic types, such as int. You need to use Integer.

When the 2.Map collection is fetched, if the variable declares a type, it will be unboxed first and then converted.

Null pointer problem

As shown in the figure, a null pointer exception occurred when the program reached line 27. Logically speaking, there are Key and Value for Map collections, and only Value for Collection collections. If the get () method is executed, the corresponding should return null when there is no key.

Map.get (s.charAt (I))

Therefore, since there is no key ")", you should return null

But reported a null pointer exception.

Reason

Map.get (s.charAt (I)); will first return the original data type Character. When the data is null, unpacking and converting it to null will throw a null pointer exception.

The following is the same.

When making if judgment, the map.get () method converts the fetched Character into a variable of the same type of expression, because an exception will be thrown when the null is unboxed into char.

Map.get, be careful that get gives a null pointer

The map.get,get may be empty. Be sure to judge before processing with a parameter, or use getOrDefault.

The above is all the contents of this article entitled "how to solve the problem that Map collections use the get method to return null throwing null pointer exceptions". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report