2012-12-11 26 views
0

我添加到哈希表方法失敗,我做了什麼錯了?或者我錯過了什麼?哈希表接口,用於設置對象的實例的鍵

測試:

@Test 
public void testAddKeyValue() { 
    AdminController cont = new AdminController(); 

    Apartment o1 = new Apartment(1, 4, "Maier B", true); 
    ArrayList<Expense> exp = new ArrayList<>(); 

    cont.addKeyWithList(o1, exp); 
    assertTrue(cont.isEmpty()); // ISSUE > the test works if it is true, but it is supposed be False. 
} 

回購類:

public class Repository extends HashMap<Apartment, ArrayList<Expense>>{ 
    private Map<Apartment,ArrayList<Expense>> dic; // last expense object refers to curret month 
    Iterator<Map.Entry<Apartment, ArrayList<Expense>>> it; 
    public void addKeyWithList(Apartment apt, ArrayList<Expense> exp){ 
     dic.put(apt, exp); 
     } 
} 

爲什麼不工作我的測試?或者在代碼中我做錯了什麼?

+0

是你的代碼拋出異常?或者它只是沒有將元素添加到散列表? – PermGenError

+0

您是否爲要放入Hashtable的類實現了equals()和hashcode()? – ntalbs

+1

我也不明白爲什麼你的類'擴展了HashMap >'並且有一個相同類型的成員變量。 – jlordo

回答

2

不要像你在做的那樣擴展HashMap。使用HashMap和委託給它:

public class Repository { 
    private Map<Apartment, List<Expense>> dic = new HashMap<Apartment, List<Expense>>(); 

    public void addKeyWithList(Apartment apt, ArrayList<Expense> exp){ 
     dic.put(apt, exp); 
    } 

    public boolean isEmpty() { 
     return dic.isEmpty(); 
    } 
} 

目前,信息庫是一個HashMap,但你不存儲任何東西:你存儲在包含在庫的另一個HashMap中的值。

此外,在字段中存儲迭代器是一個壞主意。迭代器只能使用一次。一旦它們迭代了,就不能迭代了。它應該是一個局部變量。

0

寧可延伸HashMap<Apartment, ArrayList<Expense>>,因爲它不尋常,你只是創建一個像你已經在你的課堂上創建的變量。並執行你所需的方法根據你喜歡isEmpty():

public class Repository { 
    private Map<Apartment,ArrayList<Expense>> dic; // last expense object refers to curret month 
    Iterator<Map.Entry<Apartment, ArrayList<Expense>>> it; 
    public void addKeyWithList(Apartment apt, ArrayList<Expense> exp){ 
     dic.put(apt, exp); 
     } 

    public boolean isEmpty() { 
     return dic.isEmpty(); 
    } 
} 
相關問題