Reputation: 78096
I am getting a NullPointerException while creating a TreeMap.
Here is my code:
public TreeMap<AccountGroupBean,List<AccountBean>> getAccountsAndGroups() throws SessionExpiredException {
TreeMap<AccountGroupBean,List<AccountBean>> map = new TreeMap<AccountGroupBean,List<AccountBean>>();
List<AccountGroupBean> groups = getAccountGroups();
for(AccountGroupBean group : groups) {
List<AccountBean> accounts = getAccountsByGroupId(group.getId());
System.out.println("PRINT"+ accounts.size());
map.put(group,accounts);
System.out.println("!" +map.get(group).size());
}
return map;
}
The first println prints 44. That it is to say is not null. However, the second println raises the null exception.
Any idea what I am doing wrong?
AS pointed in the accepted solution. The problem was in my implementation of compareTo.
I used to have:
public int compareTo(AccountGroupBean o) {
return (number > o.getNumber()) ? 1 : -1;
}
Adding a 0 return solved the issue:
public int compareTo(AccountGroupBean o) {
if(number == o.getNumber()) {
return 0;
}
return (number > o.getNumber()) ? 1 : -1;
}
Upvotes: 1
Views: 2944
Reputation: 8722
This is most likely a problem with how the AccountGroupBean class is implementing equals and hashcode. There are some rules fro implementing equals and hashcode that you should make sure your code complies to. Some of the rules for the equals method include.
x.equals(x)
is always truey.equals(x)
must return true if and only if x.equals(y)
is truex.equals(y)
is true and y.equals(z)
is true then x.equals(z)
must also be trueUpvotes: 1
Reputation: 12770
I looks like AccountGroupBean
doesn't implement Comparable
in a proper way, try to println group.compareTo(group)
to check if it prints 0
.
Upvotes: 2