将一个帐户对象添加到另一个帐户对象

时间:2018-02-28 12:34:14

标签: java

private HashMap<Integer, Account> accountMap;

此地图中有帐户对象。

我想要做的是按键合并对象,然后将帐号2对象添加到帐户1,并从地图中删除帐户2。

此方法属于银行类:

public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);

x.add(accountMap.get(uid1),accountMap.get(uid2));



    }

Account.class: a1.getValuables返回列表obj:[Value:16253.0 - &gt; 100.0gr金]

public class Account{

    private final int uid;
    private final List<Valuable> valuables;

    public Account(int uid) {
        this.uid = uid;
        valuables = new ArrayList<>();
    }

    public void addValuable(Valuable valuable){
        valuables.add(valuable);
    }

    /*implementation of getTotalValue method comes here*/

    public double getTotalValue​(){



return 0;
        //returns total amount of valuables present in that account
    }
public Account add(Account a1,Account a2){
Account mergedaccount;

 mergedaccount = a1.getValuables()+a2.getValuables() // something like this...

return mergedaccount;

}


    public int getUid() {
        return uid;
    }


    public List<Valuable> getValuables() {
        return valuables;
    }


    public void sortValuables(){
        Collections.sort(valuables);
    }

    @Override
    public String toString() {
        return "uid:" + uid + " " + valuables;
    }
}

Bank.class:

public class Bank {

    private HashMap<Integer, Account> accountMap;
    private Account merged;
    public Bank() {

        accountMap = new HashMap<>();

    }

    /*implementation of createAccount method comes here*/
    public void createAccount(int uid){

        for (HashMap.Entry<Integer, Account> entry : accountMap.entrySet()) {
            if(entry.getKey() == uid){

                throw new IllegalArgumentException();

            }
        }
        accountMap.put(uid,new Account(uid));

 // creates an account of id uid, if that account already exists an exception is thrown


    }


    public Account getAccount(int uid){
        return accountMap.get(uid);
    }

    @Override
    public String toString() {
        Collection<Account> accounts = accountMap.values();
        return accounts.toString();
    }

    public void addValuable(int uid, Valuable valuable) {
        if(accountMap.get(uid) ==null){

            System.out.println("valuables could not be added, no such account");
            return;
        }else{

            accountMap.get(uid).addValuable(valuable);

        }

        //Add valuable to an existing account, if the account does not exist, an error message should be printed.

    }

    public void combineAccounts(int uid1, int uid2) {
Account x = new Account(uid1);

x.add(accountMap.get(uid1),accountMap.get(uid2));



    }


    public void closeAccount(int uid) {

        if(accountMap.get(uid) != null){
            accountMap.remove(uid);
        }else{

            throw new IllegalArgumentException();
        }

    }
}

0 个答案:

没有答案