2010-11-08 49 views
1

我在创建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;  
} 
+0

stacktrace会有帮助... – 2010-11-08 11:38:23

+0

'AccountGroupBean'重写'hashcode()'和'equals()'吗? – Qwerky 2010-11-08 11:42:42

+0

你是否简化了SO的代码示例,并删除了一些关键的东西?我能想到的具体事情是TreeMap构造函数中的一个自定义比较器,它是比较器,它正在崩溃而不是放在put上? – Rich 2010-11-08 12:00:56

回答

2

我看起来像AccountGroupBean以适当的方式并没有实现Comparable,尽量给println group.compareTo(group)检查,如果它打印0

1

这是最有可能与AccountGroupBean类是如何实现equals和hashCode的一个问题。有一些规则实现equals和hashcode,你应该确保你的代码符合。 equals方法的一些规则包括。

  • 自反对于任何非空值x.equals(x)始终为true
  • 对称的非NULL值y.equals(x)当且仅当x.equals(y)是真的
  • 传递非空值,如果必须返回true x.equals(y)为真,y.equals(z)为真然后x.equals(z)也必须为真
  • Consistant如果对象没有被修改,equals方法应该在多个调用期间返回相同的答案。
  • 如果两个对象相等,它们的hashcoe方法应返回相同的值。
+0

我没有实现equals或hashcode。我是不是该? – 2010-11-08 11:57:40

+1

@Sergio,除非你想考虑AccountGroupBean的几个实例,否则例如新的AccountGroupBean(1).equals(新的AccountGroupBean(1))将会是false,除非你实现了equals,并且如果你实现了equals,你也应该实现哈希码一致... – pgras 2010-11-08 12:03:28

+1

这是有用的信息,但TreeMap依赖于compareTo而不是哈希码,并且就像一个哈希映射... – pgras 2010-11-08 12:06:30

相关问题