Hashtable接口,用于设置键的对象实例

时间:2012-12-11 11:11:16

标签: java hashtable

我对哈希表方法的添加失败了,我做错了什么?或者我错过了什么?

试验:

@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);
        }
}

为什么我的测试不起作用?或者在代码中我做错了什么?

2 个答案:

答案 0 :(得分: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();
    }
}

目前,Repository是一个HashMap,但您不会在其中存储任何内容:将值存储在Repository中包含的另一个HashMap中。

此外,将迭代器存储在字段中是一个坏主意。迭代器只能使用一次。一旦他们迭代,就不能再迭代了。它应该是一个局部变量。

答案 1 :(得分: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();
   }
}