2010-11-08 29 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

相關問題