Get the App
SLTechnology News&Howtos  ›  Development  › 

How to solve the problem that Map collection uses get method to return null and throw null pointer exception

Shulou Source: shulou.com Published: 2022-06-03 14:55:10 09月21日 Update

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!

Tags: Pointer method type problem content variable data article value interest preface reason original parameter only object partner more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft vpn NVidia Shulou Tech Info Docker