Skip to content
Advertisement

TreeSet throws nullpointer exception when using custom comparator

I got an error msg when I trying to remove a specific element in treeset (not null). I’m not sure why this happened, and I tried to use contains to check if there has the same element in the set already which would work fine. The exception throws when calling reset method.

JavaScript

Here is my code:

JavaScript

Advertisement

Answer

As @VGR mentioned: Are you certain that HS.get(a) never returns null in your compare method?

This is because that the TreeMap is based on HashMap to compare. If delete the HS value using HS.remove(a), whenever the treemap call HS.get(a) there will be a null as return value. which when called in compare for HS.get(a).compareTo will be null.compareTo, and this is the reason that throws an NullPointerException.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement