1

The system I try to debug is relatively complex, so I'll limit it to the classes/methods that I assume to cause the Nullpointer.

I have a class Cloudlet which among other fields has a unique int cloudletId used to identify it. I have a class Task extends Cloudlet. I have a hashMap HashMap<Task,Double> averageComputationTimes. I have a List<Cloudlet> cloudlets that contains all the cloudlet objects of interest.

I populate averageComputationCosts like this:

for (Object cloudlet : getCloudletList()) {
    Task t = (Task) cloudlet;
    double sum = computationCosts.get(t).values().stream().reduce(0.0,Double::sum);
    averageComputationCosts.put(t, sum/computationCosts.get(t).size());
} 

At another place in my code I get a Nullpointer:

double max = averageComputationCosts.get(task); // task is again cast and taken from getCloudletList()

Can this happen because the Task objects that are created are cast from Cloudlet and hence have a different hashCode value?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • If both theses snippets cause an NPE, have you checked that `averageComputationCosts` or its entries are not `null`? – f1sh Jul 12 '22 at 11:06
  • No, the cast doesn't change the reference/value of the object. If you get null pointer, is because the map averageComputationCosts doesn't contain the task you're searching. – Matteo NNZ Jul 12 '22 at 11:06
  • @f1sh OP gets an NPE because of the unboxing of a null into a primitive, the null coming because the task looked for has no equivalent hash in the map. While the duplicate you reference is very often the answer, I don't think it is this time. – Matteo NNZ Jul 12 '22 at 11:08
  • Have you defined the contract of Task objects? specifically equals() and hashCode() ? – Noya Jul 12 '22 at 11:12
  • 2
    @MatteoNNZ the cause is still the same. OP accesses hashmap entry with a `null` value. The reason i marked it as a duplicate is that the process of finding out what exactly is `null` is the same: looking at the stacktrace. The autounboxing is just one more circumstance. – f1sh Jul 12 '22 at 11:15
  • @f1sh I disagree, the issue here is that the task used to get from the map is not found, maybe because it's really not there, maybe because the equals/hashCode are not correctly implemented for Task class. It happens to raise a NPE because of the unboxing but it's just a side effect in this case. Anyway, it seems you outnumber me on that :) – Matteo NNZ Jul 12 '22 at 12:19

0 Answers0