Question

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?

Solution

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;       
}
Was it helpful?

Solution

I looks like AccountGroupBean doesn't implement Comparable in a proper way, try to println group.compareTo(group) to check if it prints 0.

OTHER TIPS

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.

  • Reflexive for any non null value x.equals(x) is always true
  • Symetric for non null values y.equals(x) must return true if and only if x.equals(y) is true
  • Transitive for non null values if x.equals(y) is true and y.equals(z) is true then x.equals(z) must also be true
  • Consistant The equals method should return the same answer during multiple invocations if the objects have not been modfied.
  • If two objects are equal their hashcoe method should return the same value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top