2012-12-11 23 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(); 
    } 
} 
相关问题