How do I fix this dereference of nullable error?

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)) {
   pluto.get(boxer.getName()).add(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)) {
                pluto.get(boxer.getName()).add(boxer);
        }
}

But this also doesn't work. Please help.

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

2 answers

  • answered 2018-11-08 05:47 Abhishek

    What if your map is null?

    try this:

    if (isNull(pluto)) { // import static java.util.Objects.isNull;
       return;        // to minimise nesting
    }
    
    Optional.ofNullable(pluto.get(boxer.getName()))
            .filter(value -> !value.isEmpty())
            .ifPresent(value -> { /*do whatever you want*/ });
    

  • answered 2018-11-08 05:56 efex09

    Try this. You need to check for nulls.

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