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?
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;
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With