Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an object with a data member with a unique value in Java?

Tags:

java

I'm doing a Java task that is like a simple bank system with Customer objects and SavingsAccount. I store all Customer objects in an arraylist and I was also planning to do the same with the SavingsAccount objects, but that is perhaps not necessary. Each SavingsAccount has a data member called accountNumber that is unique.

The SavingsAccount also include data members lika accountBalance. So my question is how do I reach a SavingsAccount that has the accountNumber equal to "1002" (For some reason I have them as Strings) and then be able to set or get values from data member, like accountBalance with setAccountBalance? Help is preciated! Thanks!

I create the account object

SavingsAccount account = new SavingsAccount(inAccount);

The class SavingsAccount:

class SavingsAccount {

// data members
private String accountType;
private String accountNumber;
private double accountInterestRate;
private int accountBalance;

// constructor
public SavingsAccount(String inNumber){
    accountType = "Saving";
    accountNumber = inNumber;
    accountInterestRate = 0.5;
    accountBalance = 0;
}

// get account number
public String getAccountNumber() {
    return accountNumber;
}

// get account balance
public int getAccountBalance() {
    return accountBalance;
}

// get interest rate
public double getAccountInterestRate(){
    return accountInterestRate;
}

    // set new value to balance
    public void setAccountBalance(int inMoney){
    accountBalance = accountBalance + inMoney;
    }

}

EDIT:

Since I'm learning Java, I prefer a solution that is not to complicated to use right now. I know how to use arraylist, but I haven't reach to the hashmap yet, and was hoping for a simplier, but perhaps not the best, solution for now? Isn't there a way to reach objects without "collecting" them in arraylist or hashmap?

like image 879
3D-kreativ Avatar asked Nov 13 '22 13:11

3D-kreativ


1 Answers

Instead of storing the accounts in an ArrayList<SavingsAccount> I suggest you store them in a HashMap<String, SavingsAccount>.

Put the account into the map right after creating it:

SavingsAccount account = new SavingsAccount(inAccount);
accountMap.put(inAccount, account);

You can then get hold of an account easily and efficiently by doing

accountMap.get(accountNumber);

To make sure that an account mapped to by some account number always indeed has that very account number, I suggest you make accountNumber final:

...
private final String accountNumber;
...
like image 95
aioobe Avatar answered Nov 16 '22 03:11

aioobe