ArrayLists
The Aims
In this exercise, you will convert the code that uses an array into an ArrayList.
Creating an ArrayList
Using the TestAccount2 class:
-
Create a new ArrayList to replace the array called accounts.
-
Change each of the lines that adds an account into the array to instead add an account into the arraylist.
-
Modify the loop and all other code in the class, so that the class compiles.
Click here to see the sample solution
import java.util.ArrayList;
import java.util.List;
public class TestAccount2 {
public static void main(String[] args) {
List<Account> accounts = new ArrayList<>();
try {
accounts.add(new Account(1000.0, "Fingers", AccountType.CHECKING));
} catch (DodgyNameException e) {
System.out.println(e.getMessage());
}
try {
accounts.add(new Account(2000.0, "Bob", AccountType.CHECKING));
} catch (DodgyNameException e) {
System.out.println(e.getMessage());
}
try {
accounts.add(new Account(1500.0, "Charlie", AccountType.SAVING));
} catch (DodgyNameException e) {
System.out.println(e.getMessage());
}
try {
accounts.add(new Account(1500.0, "Charlie", AccountType.SAVING));
} catch (DodgyNameException e) {
System.out.println(e.getMessage());
}
try {
accounts.add(new Account(2500.0, "Eve", AccountType.CREDIT_CARD));
} catch (DodgyNameException e) {
System.out.println(e.getMessage());
}
Account.setInterestRate(0.07);
for (int i = 1; i < accounts.size(); i++) {
System.out.println("Account: " + accounts.get(i));
accounts.get(i).addInterest();
System.out.println("Balance after interest: " + accounts.get(i).getBalance());
System.out.println();
}
System.out.println(accounts.get(2).equals(accounts.get(3)) ? "account 2 and 3 are equal" : "account 2 and 3 are not equal");
System.out.println(accounts.get(2).equals(accounts.get(4)) ? "account 2 and 4 are equal" : "account 2 and 4 are not equal");
accounts.get(0).withdraw(100);
accounts.get(1).withdraw();
accounts.get(2).withdraw(2500);
}
}