Array Lists   Click here for the syntax in Java 7

ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();

accounts.add(new BankAccount(1001));

accounts.add(new BankAccount(1015));

accounts.add(new BankAccount(1022));

Retrieving Array List Elements

BankAccount anAccount = accounts.get(2); // gets the third element of the array list

int i = accounts.size();

anAccount = accounts.get(i); // Error

//legal index values are 0. . .i-1

Adding /Removing /Changing Values of Elements

BankAccount anAccount = new BankAccount(1729);

accounts.set(2, anAccount);

accounts.add(i, a)

1. Resize the array list (increase by one)

2. copy the last one to the new spot. Keep moving until the space of i is available.

To remove an element at an index, use the remove method:

 account.remove(1);

 


Click here for an example.

How do you construct an array of 10 strings? An array list of strings?

   Answer:

  new String[10];

  new ArrayList<String>();


What is the content of names after the following statements?   

       ArrayList<String> names = new ArrayList<String>();   

   names.add("A");

   names.add(0, "B");

   names.add("C");

   names.remove(1);

   Answer: names contains the strings "B" and "C" at positions 0 and 1