Java 哈希表接口,用于设置对象实例的键

Java 哈希表接口,用于设置对象实例的键,java,hashtable,Java,Hashtable,我的add-to-hashtable方法失败,我做错了什么?或者我误解了什么 测试: @测试 公共无效testAddKeyValue(){ AdminController cont=新的AdminController(); 公寓o1=新公寓(1,4,“Maier B”,正确); ArrayList exp=新的ArrayList(); cont.addKeyWithList(o1,exp); assertTrue(cont.isEmpty());//ISSUE>如果测试为true,则测试有效,但

我的add-to-hashtable方法失败,我做错了什么?或者我误解了什么

测试:

@测试
公共无效testAddKeyValue(){
AdminController cont=新的AdminController();
公寓o1=新公寓(1,4,“Maier B”,正确);
ArrayList exp=新的ArrayList();
cont.addKeyWithList(o1,exp);
assertTrue(cont.isEmpty());//ISSUE>如果测试为true,则测试有效,但假设为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);
        }
}
公共类存储库扩展HashMap{
私有映射dic;//上一个费用对象指当前月份
迭代器;
公共无效addKeyWithList(公寓公寓公寓,ArrayList exp){
dic.put(apt,exp);
}
}

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

不要像现在这样扩展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();
    }
}
公共类存储库{
私有映射dic=新HashMap();
公共无效addKeyWithList(公寓公寓公寓,ArrayList exp){
dic.put(apt,exp);
}
公共布尔值为空(){
返回dic.isEmpty();
}
}
目前,存储库是一个HashMap,但您不在其中存储任何内容:您将值存储在存储库中包含的另一个HashMap中


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

而不是扩展
HashMap
,因为创建一个与类中已经创建的变量类似的变量是不寻常的。并根据需要实现所需的方法,如isEmpty():

公共类存储库{
私有映射dic;//上一个费用对象指当前月份
迭代器;
公共无效addKeyWithList(公寓公寓公寓,ArrayList exp){
dic.put(apt,exp);
}
公共布尔值为空(){
返回dic.isEmpty();
}
}

您的代码是否引发异常??或者只是没有将元素添加到哈希表中??您是否为要放入哈希表中的类实现了equals()和hashcode()?我也不明白为什么您的类
扩展了HashMap
,并具有相同类型的成员变量。此外,您正在创建addKeyWithList()方法,并且您正在使用AdminController类。这两个类是相同的还是什么。。?你能解释一下你在做什么吗。。?还有,你想归档什么。。?
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();
    }
}
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();
   }
}