If you are interested in structure which could dynamically grow in size and let you map one value into another (like accountNumber -> amount) then you may be interested in Map
. You could use for instance
Map<int,double> map = new HashMap<int,double>();
where int
is type we use as key - account number, and double
is value which will be connected with key (in reality double
is not best type to store informations about amount of money, you would probably use something like BigDecimal
, but for now lets leave double
).
To put
informations about account and its amount to map just use
map.put(1, 42);
which would bound key 1
with value 42
.
To update amount stored in account with number 1 and lets say add 3 dollars just get
current amount from account number you are interested in, calculate new value and put it in map like
map.put(1, map.get(1)+3);
In case you really must use Lists you can try to use advantage of fact that Java is object oriented language. Create your ow class which will represent account. Such class should have number
and amount
fields. It can look like
class Account {
// fields representing state of Account
private int number;
private double amount; //again in real world double would not be best choice
//and you would use something like BigDecimal
// getters and setters
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
// constructor
public Account(int number, double amount) {
this.number = number;
this.amount = amount;
}
}
and create list of instances of such class. You can create such list with
List<Account> accounts = new ArrayList<Account>();
Notice that used List
as type of reference List<Account> accounts
not ArrayList<Account> accounts
because generally it is better to program on interface.
To add new accounts to such list just use add
method like
accounts.add(new Account(1, 42));
accounts.add(new Account(2, 200));
accounts.add(new Account(3, 60));
which will add new Account instances. Notice that with this approach nothing stops you from creating few instances of Account class representing same account number which would be impossible with mentioned earlier Map approach (each key in Map can hold only one value and using put
with already used key will replace old value with new one).