0

To my understanding following code should run fine.

However, When I try to compile, it is failing at compareTo

public class Test {

    Comparable<?> getMinimum() {
        return null;
    }

    public int getPreviousValue(double nv) {
        return getMinimum().compareTo(nv);
    }
}

So my question is why compilation if failing - are we not allowed to compare null with double?

T-Bag
  • 10,916
  • 3
  • 54
  • 118

3 Answers3

3

The problem here is not the null result of that method.

The problem is that the compiler doesn't know how you could call compareTo(double) on something that your getMinimum() returns.

You have to change the the signature to Comparable<Double> getMinimum() to make it work! You can only compare against a specific type of number if your Comparable supports that!

Of course, at runtime, you will then face a NPE. And also of course: some code inspection tools could identify this specific NPE situation already at compile time.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

Compiler is getting confused at Comparable<?>. Make the Comparable of specific type (Double in you case) to make the compiler happy. :)

public class Test {

    Comparable<Double> getMinimum() {
        return null;
    }

    public int getPreviousValue(double nv) {
        return getMinimum().compareTo(nv);
    }
}
S.K.
  • 3,597
  • 2
  • 16
  • 31
1

You don't have a nullpointer, you have a problem invoking compareTo with argument double NOT Double!

fl0w
  • 3,593
  • 30
  • 34