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.
java.lang.NullPointerException at line 55, Leaderboard$1.compare at line 52, Leaderboard$1.compare at line 374, java.base/java.util.TreeMap.getEntryUsingComparator at line 343, java.base/java.util.TreeMap.getEntry at line 601, java.base/java.util.TreeMap.remove at line 276, java.base/java.util.TreeSet.remove at line 86, Leaderboard.reset at line 71, __Driver__.__helperSelectMethod__ at line 91, __Driver__.__helper__ at line 112, __Driver__.main
Here is my code:
class Leaderboard { TreeSet<Integer> TS; HashMap<Integer, Integer> HS = new HashMap<>(); public Leaderboard() { TS = new TreeSet<>(new Comparator<Integer>(){ @Override public int compare(Integer a, Integer b){ if(HS.get(a).equals(HS.get(b))){ return Integer.compare(a, b); } return HS.get(a).compareTo(HS.get(b)); } }); } public void addScore(int playerId, int score) { HS.put(playerId, HS.getOrDefault(playerId, 0) + score); TS.add(playerId); TreeSet<Integer> test = TS; HashMap<Integer, Integer> test2 = HS; } public int top(int K) { Iterator<Integer> iterator = TS.iterator(); int res = 0; while(K > 0 && iterator.hasNext()){ res += HS.get(iterator.next()); K--; } return res; } public void reset(int playerId) { Integer id = new Integer(playerId); //tried, not work System.out.println(HS.containsKey(id)); // true System.out.println(TS.contains(id)); // true HS.remove(id); TS.remove(id); } } /** * Your Leaderboard object will be instantiated and called as such: * Leaderboard obj = new Leaderboard(); * obj.addScore(playerId,score); * int param_2 = obj.top(K); * obj.reset(playerId); */
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.