Answer the question
In order to leave comments, you need to log in
Is it necessary to check Map for null?
Good afternoon!
I have some function:
public Map<String, Object> getTestMap(MyClass myObject) {
Map<String, Object> myResultMap = new HashMap<String, Object>();
myResultMap.put("myKey", myObject.getMyValue());
return myResultMap;
}
Map<String, Object> resultMap = getTestMap(myObject);
resultMap
for in the future null
when I want to get values by key? Map<String, Object> resultMap = getTestMap(myObject);
if (resultMap != null) {
Object myObject = resultMap.myKey;
}
Answer the question
In order to leave comments, you need to log in
1. You are incorrectly extracting a value from map by key, you should use the get -> resultMap.get(myKey) method;
2. Checking for null when referring to resultMap is not needed, because you create an empty map in the getTestMap method and resultMap is never null;
3. Checking for null is needed in the getTestMap method because you call myObject.getMyValue() without checking for null, here NullPointerException can occur if the method is called with a parameter whose value is null.
In order to avoid such questions, I recommend marking all methods, arguments and fields with @NonNull and @Nullable.
All fields and local variables that do not change logically are final.
Declaration of variables as close as possible to the place of their use.
The answer to the question is no, in this case it is not necessary to check. But if the method is library and is not marked with an annotation - it is necessary.
It’s even better to take Kotlin and not suffer :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question