How do I fix this dereference of nullable error?

3484 views java

I've been trying to get rid of the dereference of a possible null-reference graph for the longest time, but nothing seems to work.

This is my original code:

if (!pluto.get(boxer.getName()).contains(boxer)) {

where pluto is private final Map> pluto;

and I have also tried

if (pluto.get(boxer.getName()) != null) {
        if (!pluto.get(boxer.getName()).contains(boxer)) {

But this also doesn't work. Please help.

[dereference.of.nullable] dereference of possibly-null reference pluto.get(boxer.getName())

answered question

What pluto.get(boxer.getName()) returns?

can you please share full code?

it returns the set of strings that it is mapped to. I don't know why, but stack overflow removed my implementation for my graph. it is private final Map<String, Set<String>> pluto

There might be two possibility one map is null and another possibility is boxer.getName is null also you can verify by run your code is debug mode so you can inspect the element and check what is getting null.

2 Answers


What if your map is null?

try this:

if (isNull(pluto)) { // import static java.util.Objects.isNull;
   return;        // to minimise nesting

        .filter(value -> !value.isEmpty())
        .ifPresent(value -> { /*do whatever you want*/ });

posted this

Try this. You need to check for nulls.

if (pluto != null && pluto.get(boxer.getName()) != null && !pluto.get(boxer.getName()).contains(boxer)) {

posted this

Have an answer?


Please login first before posting an answer.