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

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

4

2 回答 2

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 中。

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

于 2012-12-11T11:20:28.483 回答
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();
   }
}
于 2012-12-11T11:24:54.907 回答