我在创建TreeMap时遇到NullPointerException。填充TreeMap抛出NullPointerException
这里是我的代码:
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;
}
第一的println打印44.这是这么说是不为空。但是,第二个println引发null异常。
任何想法我做错了什么?
解决方案
正如接受的解决方案中指出的那样。问题出在我的compareTo实现上。
我曾经有:
public int compareTo(AccountGroupBean o) {
return (number > o.getNumber()) ? 1 : -1;
}
添加0回报解决了问题:
public int compareTo(AccountGroupBean o) {
if(number == o.getNumber()) {
return 0;
}
return (number > o.getNumber()) ? 1 : -1;
}
stacktrace会有帮助... – 2010-11-08 11:38:23
'AccountGroupBean'重写'hashcode()'和'equals()'吗? – Qwerky 2010-11-08 11:42:42
你是否简化了SO的代码示例,并删除了一些关键的东西?我能想到的具体事情是TreeMap构造函数中的一个自定义比较器,它是比较器,它正在崩溃而不是放在put上? – Rich 2010-11-08 12:00:56