ArrayLists
Objective #1: Be familiar with ArrayLists and use their available methods.
- An ArrayList is an object that can be used to store multiple objects. in other words, with one ArrayList you can store many strings or many numbers instead of just one item like a plain variable. An ArrayList is similar to an array.
- The ArrayList class is built into Java but you must type the following statement at the top of your file in order to use ArrayLists.
import java.util.ArrayList;
- The following statement only declares an ArrayList so that it can store Bug objects. The statement does not instantiate the ArrayList.
ArrayList<Bug> bugCollection;
- The following statement declares and instantiates an ArrayList so that it can store Bug objects
ArrayList<Bug> bugCollection = new ArrayList<Bug>();
- Like an array, the first element of an ArrayList has an index (i.e.
subscript) of zero.
- Square brackets cannot be used with ArrayLists as they are with arrays. Instead the following important methods of the ArrayList class are used:
- add - adds a new element to the end of an ArrayList or inserts a new element into the middle of an ArrayList
- get - accesses one element in an ArrayList
- set - overrides an element in ArrayList with a new value and returns the old value
- remove - removes an element out of an ArrayList and returns the value that was removed
- size - returns the number of elements in an ArrayList
- Usually ArrayList's are used to store objects (like String's, Bug's, etc.) rather than primitive data types like int's
and double's. But the current version of Java will allow you to store int's
and double's in an ArrayList since Java will "autobox" the numbers as Integer (or Double) objects as it transfers them in and out of the ArrayList.
- Behind the scenes, an ArrayList is really a standard array (explained below). That is, an array is a property in the ArrayList class and when an ArrayList is instantiated via a constructor, it's really simply creating a standard array. When its default constructor
is used, an ArrayList has an initial capacity and size of zero. An ArrayList automatically resizes itself when it runs
out of space. Its capacity is doubled. Actually, a new standard array is
created and the values stored in the original array are copied into the new,
larger array. The old array is garbage-collected. Therefore, unlike a
standard array, which must be declared to a specific, fixed size, an ArrayList is dynamic.
Objective #2: Be able to use the ArrayList get method.
- The get method
is used to access the element stored at a given position. For example bugCollection.get(3) would
return the Bug stored
in index position 3 of bugCollection.
Therefore the statement:
System.out.println(bugCollection.get(3));
can be used to print the fourth Bug object (assuming that the toString method is implemented in the Bug class). Note that it is the fourth Bug, not the third Bug, that would be found in subscript position 3.
Also, the get method could be used to store that reference in the object variable fred
Bug fred = bugCollection.get(3);
- A for loop can be used to traverse through an ArrayList using the get method as in
for (int i = 0; i < scores.size(); i++)
{
System.out.println(scores.get(i));
}
Objective #3: Be able to use the ArrayList add method.
- There are two versions of the overloaded add method. One version of add takes one parameter and simply adds the parameter to the end of the ArrayList. For example,
if the ArrayList scores stored the values 22, 33, 44, 55, 66 in positions 0 through 4, then after the line of code scores.add(88); executes,
the ArrayList would hold the values 22, 33, 44, 55, 66, 88 since the 88 is added to the very end of the ArrayList.
In the following example, "Penn State" is added to the end of an existing ArrayList named colleges:
String name = "Penn State";
colleges.add(name);
- The other
overloaded version can be used to add something to the end of the ArrayList.
A boolean true value is returned if it is successfully added. For example, if the ArrayList scores stored the values 22, 33, 44, 55,
66 in positions 0 through 4, then after the line of code scores.add(1, 88); executes, the ArrayList would
hold the values 22, 88, 33, 44, 55, 66 since the 88 is inserted into position 1 and everything else shifts back one position.
In the following example, "Penn State" is inserted to subscription position 2 of the existing ArrayList named colleges. Any elements that are behind "Penn State" are pushed back:
String name = "Penn State";
colleges.add(2, name);
After any given call to the add method,
the size of an ArrayList automatically increases by one.
Objective #4: Be able to use the ArrayList size method.
- The size method returns the number of values that
are currently stored in an ArrayList. The default constructor of ArrayList sets the size of an ArrayList to 0.
- You can access the very last element of an ArrayList using the size method. For example, no matter what size the ArrayList bugCollection has, the following code would display the
last item (using the class's toString method)
System.out.println(bugCollection.get(bugCollection.size() - 1);
- It is important to
use the size method
correctly and to subtract one when appropriate to avoid having a bounds
error where
you are attempting to access an invalid position of an array list. The JVM will throw a runtime IndexOutOfBoundsException in
such cases and terminate the program. The following statement would cause
this error:
System.out.println(bugCollection.get(bugCollection.size());
Objective #5: Be able to use the ArrayList remove method.
- The remove method
is used to remove a value at a given position. All of the values "behind" that
position are shifted forward in the ArrayList.
The old value that was stored in the position is returned. For example, if the ArrayList scores stored the values 22, 33, 44, 55, 66
in positions 0 through 4, then after the line of code scores.remove(1); executes,
the ArrayList would hold the values 22, 44, 55, 66.
Or it could be used in this way. If the ArrayList holds the values 22, 33, 44, 55, 66 then the statement
System.out.println(scores.remove(1));
which would cause the value 33 to be displayed even though the 33 is now permanently removed from the ArrayList.
- The remove method returns the value being returned. So you can also make use of the removed value as in
ArrayList<String> roster = new ArrayList<String>();
roster.add("alfred");
roster.add("bill");
roster.add("charlie");
String name = roster.remove(1);
where the variable name now contains "bill" but roster only contains {"alfred", "charlie"}
Objective #6: Be able to use the ArrayList set method.
- The set method is used
to assign the value of an element at a given subscript position thus overwriting an existing element.
The old value stored in that position is returned though in case the client programmer wants to make use of it. For example, if the ArrayList scores stored the values 22, 33, 44, 55, 66 in positions
0 through 4, then after the line of code scores.set(1, 88); executes, the ArrayList would
hold the values 22, 88, 44, 55, 66 since the 33 in subscription position 1 is overwritten with the value 88. Or it could be used in this way
System.out.println(scores.set(1, 88));
in which case the "old" value in subscript position one 33 would print out but be overwritten with the "new" value of 88 in subscript position 1.
- The set method returns the value being overwritten. So you can also make use of this overwritten value as in
ArrayList<String> roster = new ArrayList<String>();
roster.add("alfred");
roster.add("bill");
roster.add("charlie");
String name = roster.set(1, "bonnie");
where the variable name now contains "bill" and roster contains {"alfred", "bonnie", "charlie"}
Objective #7: Use ArrayLists in client programs.
- In a regular client program, you might use an ArrayList to store a list of your friends' names as in the following example
import java.util.ArrayList;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<String> friends = new ArrayList<String>();
friends.add("Jill Miller"); // Jill Miller
friends.add("Bill Miller"); // Jill Miller, Bill Miller
friends.add("Carly Sampson"); // Jill Miller, Bill Miller, Carly Sampson
friends.set(1, "Will Maloney"); // Jill Miller, Will Maloney, Carly Sampson
friends.add(2, "Phil Collins"); // Jill Miller, Will Maloney, Phil Collins, Carly Sampson
friends.remove(0); // Will Maloney, Phil Collins, Carly Sampson
displayInitials(friends);
System.out.println(friends);
}
public static void displayInitials(ArrayList<String> arr)
{
for (String x : arr)
{
System.out.print(x.substring(0, 1));
System.out.println(x.substring(x.indexOf(" ") + 1, x.indexOf(" ") + 2));
}
}// end of displayInitials method
Objective #8: Use ArrayLists as instance variables in classes.
- By using composition (i.e. a has-a relationship), you could use an ArrayList as an instance variable within a class as in the following example.
import java.util.ArrayList;
public class Friends
{
private ArrayList<String> myFriends; // THIS DECLARES THE ARRAYLIST ONLY BUT DOES NOT INSTANTIATE IT.
// IT SHOULD BE INSTANTIATED IN THE CONSTRUCTOR BELOW.
public Friends()
{
myFriends = new ArrayList<String>(); // THIS IS IMPORTANT, YOU SHOULD INSTANTIATE THE ARRAYLIST IN THE CONSTRUCTOR
}
public void addFriend(String name)
{
myFriends.add(name); // using the add method of the ArrayList class to add a friend to the ArrayList myFriends
}
public void displayFriends()
{
for (int i = 0; i < myFriends.size(); i++) // notice the use of < instead of <=
{
System.out.println(myFriends.get(i)); // using get method instead of square brackets like an array
}
}
}
// CLIENT PROGRAM *********************************
public class FriendsTest
{
public static void main(String[] args)
{
Friends homies = new Friends();
homies.addFriend("Jill");
homies.addFriend("Mary");
homies.displayFriends();
}
}
- You can even use an ArrayList as a property in a class is a property of yet another class!
import java.util.ArrayList;
public class Friend
{
private String myFirstName;
private String myLastName;
public Friend(String firstName, String lastName)
{
myFirstName = firstName;
myLastName = lastName;
}
public String toString()
{
return myFirstName + " " + myLastName;
}
}
// ***************************************
public class Friends
{
private ArrayList<Friend> myFriends;
public Friends()
{
myFriends = new ArrayList<Friend>();
}
public void addFriend(String firstName, String lastName)
{
myFriends.add(new Friend(firstName, lastName));
}
public void displayFriends()
{
for (Friend x : myFriends)
{
System.out.println(x);
}
}
}
// CLIENT PROGRAM *************************
public class FriendsTest
{
public static void main(String[] args)
{
Friends homies = new Friends();
homies.addFriend("Jill", "Sampson");
homies.addFriend("Mary", "Roberts");
homies.displayFriends();
}
}
Objective #9: Understand the differences between an ArrayList and
array.
-
Do not confuse
ArrayLists with arrays. On the AP exam, you typically will be expected to use an
ArrayList to store objects. You will be expected to use an array to store numerical values such as
int's or
double's (even though it is possible to store objects in an 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 #10: Understand the java.util.List interface and some of its methods.
- The ArrayList class implements the List interface that is part of Java. The ArrayList class includes the methods size, add, get, set, and remove since those methods are all found in the List interface.
- The List interface (found in the java.util package) includes the following methods:
- int size();
- boolean add(E x);
- void add(int index, E x);
- E get(int index);
- E set(int index, E x);
- E remove(int index);
- Iterator<E> iterator();
- ListIterator<E> listIterator();
- The same object can be inserted into a list several times. The same object can also belong to several lists.
- Usually, an object (except immutable String's, Integer's, & Double's) can be modified after it is inserted into a list.
- Indices are checked to be within (0, list.size() - 1) however in some implementations, methods will throw an indexOutOfBoundsException if called with an invalid index argument
Objective #11: Use "enhanced" for loops loops with ArrayLists.
- An enhanced for loop can be used to efficiently traverse an ArrayList.
- In this example
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(99);
scores.add(75);
scores.add(82);
for (Integer value : scores)
{
System.out.println(value);
}
In the loop above, each element of scores is placed into the variable value which is being declared as an Integer since the ArrayList scores is made up of Integer objects. Code inside the loop can use the variable value but, on each successive loop iteration, the value in value changes to the next element found in scores. Note that the size method does not need to be used since the computer automatically iterates to each element of scores.
- The following code segment would display the name of each Turtle object stored in an ArrayList of Turtle objects named turtleCollection
for (Turtle turtle : turtleCollection)
{
System.out.println(turtle.getName());
}
assuming of course that theTurtleclass has a getName method and turtleCollection contains a bunch of Turtle objects.
- Elements of an ArrayList cannot be modified within an enhanced for loop. The following loop would cause a runtime exception error:
for (Turtle turtle : turtleCollection)
{
turtle.setName("Mr. " + turtle.getName()));
}
The loop above should be written with a traditional for loop.
Also, you cannot or at least should not modify an ArrayList by inserting or removing elements from it. The attempt often causes a runtime exception error like the following example:
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(99);
scores.add(75);
scores.add(0);
for (Integer value : scores)
{
if (value == 0)
{
scores.add(99); // do not modify scores by adding an element to it
}
}
Instead you should use a traditional for loop as in
ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(99);
scores.add(75);
scores.add(0);
for (int i = 0; i < scores.size(); i++)
{
if (scores.get(i) == 0)
{
scores.add(99);
}
}
Objective #12: Use two-dimensional ArrayLists.
- Here is a program that illustrates the use of a two-dimensional ArrayList.
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++;
}
}
}