0

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

テストが機能しないのはなぜですか? または、コードのどこで何か間違ったことをしましたか?

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 に値を保存します。

また、イテレータをフィールドに格納することはお勧めできません。イテレータは 1 回だけ使用できます。それらが繰り返されると、それ以上繰り返すことはできません。これはローカル変数である必要があります。

于 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 に答える