ArrayLists
Objective #1: Be familiar with ArrayLists and use their available methods.
Objective #2: Use ArrayLists appropriately in client programs and as properties in classes.
Objective #3: Understand the differences between an ArrayList and array.
ArrayList |
array |
| You can only store objects. Although, if you want to store int's or double's, Java will automatically autobox them. | You can store primitive types (such as int & double) or objects |
| its size is dynamic | its length is fixed (aka static) |
| many interesting methods that you need to know for the AP exam | few methods that you need to know for the AP exam |
| myList.set(3, "hello"); | myArray[3] = "hello"; |
| myList.set(3, new Integer(12)); or myList.set(3, 12); due to automatic autoboxing |
myArray[3] = 12; |
| System.out.println(myList.get(3)); | System.out.println(myArray[3]); |
| The method size() can be used to obtain the size of an ArrayListas in System.out.println(myList.size()); | The public field length can be used to obtain the size of an array (e.g. System.out.println(myArray.length); |
| You can easily insert an element to the middle of an ArrayList (e.g. myList.add(3, "world"); works as long as ArrayList contains 3 or more elements | You cannot easily insert an element to the middle of an array though you can overwrite an existing element of an array with another value as in myArray[3] = "world"; |
Objective #4: Understand the java.util.List interface and some of its methods.
Objective #5: Use "enhanced" for loops loops with arrays and ArrayLists.
Objective #6: Use two-dimensional ArrayLists.
import java.util.ArrayList;
public class ArrayListOfArrayLists
{
public static void main(String[] args)
{
ArrayList<ArrayList<Integer>> listOfList = new ArrayList<ArrayList<Integer>>();
for (int row = 0; row < 5; row++)
{
listOfList.add(new ArrayList<Integer>());
for (int col = 0; col < 3; col++)
{
listOfList.get(row).add((int) (Math.random() * 100));
}
}
System.out.println(listOfList);
ArrayList<int[]> listOfArray = new ArrayList<int[]>();
for (int row = 0; row < 5; row++)
{
int[] array = new int[3];
for (int col = 0; col < 3; col++)
{
array[col] = (int) (Math.random() * 100);
}
listOfArray.add(array);
}
int i = 0;
while (i < listOfArray.size())
{
for (int j = 0; j < listOfArray.get(i).length; j++)
System.out.print(listOfArray.get(i)[j] + " ");
i++;
}
}
}