import java.util.ArrayList; /** This program tests the ArrayList class. */ public class ArrayListTester { public static void main(String[] args) { ArrayList<BankAccount> accounts = new ArrayList<BankAccount>(); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(1015)); accounts.add(new BankAccount(1729)); accounts.add(1, new BankAccount(1008)); accounts.remove(0); System.out.println("Size: " + accounts.size()); System.out.println("Expected: 3"); BankAccount first = accounts.get(0); System.out.println("First account number: " + first.getAccountNumber()); System.out.println("Expected: 1008"); BankAccount last = accounts.get(accounts.size() - 1); System.out.println("Last account number: " + last.getAccountNumber()); System.out.println("Expected: 1729"); } }
/** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { /** Constructs a bank account with a zero balance @param anAccountNumber the account number for this account */ public BankAccount(int anAccountNumber) { accountNumber = anAccountNumber; balance = 0; } /** Constructs a bank account with a given balance @param anAccountNumber the account number for this account @param initialBalance the initial balance */ public BankAccount(int anAccountNumber, double initialBalance) { accountNumber = anAccountNumber; balance = initialBalance; } /** Gets the account number of this bank account. @return the account number */ public int getAccountNumber() { return accountNumber; } /** Deposits money into the bank account. @param amount the amount to deposit */ public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } /** Withdraws money from the bank account. @param amount the amount to withdraw */ public void withdraw(double amount) { double newBalance = balance - amount; balance = newBalance; } /** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { return balance; } private int accountNumber; private double balance; }
Output:
Size: 3
Expected: 3
First account number: 1008
Expected: 1008
Last account number: 1729
Expected: 1729