8.2. ArrayList Methods¶
The following are ArrayList
methods that are often used in programs.
int size() returns the number of elements in the list
boolean add(E obj) appends obj to the end of the list and returns true
E remove(int index) removes the item at the index and shifts remaining items to the left (to a lower index)
void add(int index, E obj) moves any current objects at index or beyond to the right (to a higher index) and inserts obj at the index
E get(int index) returns the item in the list at the index
E set(int index, E obj) replaces the item at index with obj
8.2.1. Size()¶
As we saw in the last lesson, you can get the number of items in a ArrayList using its size()
method. The ArrayList starts out empty with a size of 0.
ArrayList<String> list = new ArrayList<String>();
System.out.println( list.size() );
Note
With arrays, you use the length
field to get the number of items in the array. But, with an ArrayList
you use the size()
method to get the number of items in the ArrayList. You will not be penalized if you mix up length and size() in the CS A exam. The number of items in an empty ArrayList is 0.
8.2.2. Add(obj) to an ArrayList¶
You can add values to an ArrayList by using the method add(obj)
which will add the object to the end of the list, just like you would join the end of the line to board a bus.
Run the code below to see how the list changes as each object is added to the end. Notice that we added the same string to the list more than once. Lists can hold duplicate objects. Can you add your name to the list and then print out the list?
When adding Integer objects to the list, you can use the Integer constructor like add(new Integer(5))
in Java version 7 which is used on the exam (although this is deprecated and no longer used in Java version 9) or you can just add the int value directly like add(5)
in any Java version and it will be changed into an Integer
object automatically. This is called autoboxing. When you pull an int
value out of a list of Integers
that is called unboxing.
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(5)); // this will only work in Java 7
list.add(5); // this will work in all Java versions
You can put any kind of Objects into an ArrayList. Even objects for a class that you wrote. For example, here is an ArrayList of Students.
An example of an ArrayList of Student objects. Add a new student with your name and info in it.
8.2.3. Add(index,obj) in an ArrayList¶
There are actually two different add
methods in the ArrayList
class. The add(obj)
method adds the passed object to the end of the list. The add(index,obj)
method adds the passed object at the passed index, but first moves over any existing values to higher indicies to make room for the new object.
What will the code below print out? Try figuring it out before running it. Remember that ArrayLists start at index 0 and that the add(index,obj) always has the index as the first argument.
Note
ArrayLists like arrays start numbering their elements from 0.
- [1, 2, 3, 4, 5]
- This would be true if all the
add
method calls wereadd(value)
, but at least one is not. - [1, 4, 2, 3, 5]
- This would be true if it was
add(1, 4)
- [1, 2, 4, 3, 5]
- The
add(2, 4)
will put the 4 at index 2, but first move the 3 to index 3. - [1, 2, 4, 5]
- This would be true if the
add(2, 4)
replaced what was at index 2, but it actually moves the value currently at index 2 to index 3.
8-2-4: What will print when the following code executes?
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(2, 4);
list1.add(5);
System.out.println(list1);
You can step through the code above by clicking on this Java Visualizer.
- ["Anaya", "Sarah", "Layla", "Sharrie"]
- The
add(1, "Sarah")
will move any current items to the right and then put "Sarah" at index 1. - ["Anaya", "Layla", "Sharrie", "Sarah"]
- This would be true if the last one was
add("Sarah")
- ["Sarah", "Anaya", "Layla", "Sharrie"]
- This would be true if the last one was
add(0, "Sarah")
- ["Anaya", "Layla", "Sarah", "Sharrie"]
- This would be true if the last one was
add(2, "Sarah")
8-2-5: What will print when the following code executes?
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Anaya");
list1.add("Layla");
list1.add("Sharrie");
list1.add(1, "Sarah");
System.out.println(list1);
You can step through the code above by clicking on the following Java Visualizer.
8.2.4. Remove(index) from ArrayList¶
You can also remove values from an ArrayList by using remove(index) to remove the item at the given index from the list. This will move all the other items over in the underlying array and decrease the size of the ArrayList by 1.
What will the following code print out? Try to guess before you run it. Were you surprised? Read the note below.
Note
The remove(int index)
method will remove the object at the index and shift left any values to the right of the current index. It doesn’t remove the object that matches the integer value given. In the example above it doesn’t remove the value 1. It removes the value 2 at index 1.
- [2, 3]
- This would be true if it was
remove(0)
- [1, 2, 3]
- The
remove
will remove a value from the list, so this can't be correct. - [1, 2]
- The 3 (at index 2) is removed
- [1, 3]
- This would be true if it was
remove(1)
8-2-7: What will print when the following code executes?
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.remove(2);
System.out.println(list1);
You can step through the code above by clicking on the following RemoveExample.
8.2.5. ArrayList get/set Methods¶
You can get the object at an index using obj = listName.get(index)
and set the object at an index using listName.set(index,obj)
. Set/Get are used after you add and remove elements to an ArrayList to change or retrieve them.
Notice that ArrayLists use set/get methods instead of using the square brackets array[index] that arrays use. This is because ArrayList is a class with methods that provide access to the underlying array.
Try to guess what the code below will print before running it. Can you get the last element in the nameList to print it out? Can you set the first element in the list to your name and print out the list?
- [1, 2, 3, 4, 5]
- The
set
will replace the item at index 2 so this can not be right. - [1, 2, 4, 5, 6]
- The
add
with an index of 2 and a value of 5 adds the 5 at index 2 not 3. Remember that the first index is 0. - [1, 2, 5, 4, 6]
- The
set
will change the item at index 2 to 4. The add of 5 at index 2 will move everything else to the right and insert 5. The lastadd
will be at the end of the list. - [1, 5, 2, 4, 6]
- The
add
with an index of 2 and a value of 5 adds the 5 at index 2 not 1. Remember that the first index is 0.
8-2-9: What will print when the following code executes?
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.set(2, 4);
list1.add(2, 5);
list1.add(6);
System.out.println(list1);
You can step through the code above by clicking on the following Example1.
- ["Sarah", "Destini", "Layla", "Sharrie"]
- Remember that the first index is 0 not 1.
- ["Sarah", "Destini", "Anaya", "Layla", "Sharrie"]
set
changes the value and the first index is 0 not 1.- ["Anaya", "Sarah", "Sharrie"]
add
at index 1 adds the new value at that index but moves right any existing values.- ["Anaya", "Sarah", "Destini", "Sharrie"]
- The list is first ["Anaya", "Layla", "Sharrie"] and then changes to ["Anaya", Destini", "Sharrie"] and then to ["Anaya", "Sarah", "Destini", "Sharrie"]
8-2-10: What will print when the following code executes?
List<String> list1 = new ArrayList<String>();
list1.add("Anaya");
list1.add("Layla");
list1.add("Sharrie");
list1.set(1, "Destini");
list1.add(1, "Sarah");
System.out.println(list1);
You can step through the code above by clicking on the following Example2.
8.2.6. Comparing arrays and ArrayLists¶
When do you use arrays and when do you use ArrayLists? Use an array when you want to store several items of the same type and you know how many items will be in the array and the items in the array won’t change in order or number. Use an ArrayList when you want to store several items of the same type and you don’t know how many items you will need in the list or when you want to remove items from the list or add items to the list while the program is running.
Here is a comparison of how to create arrays and ArrayLists:
// arrays must specify a size!
int[ ] highScores = new int[5];
String[ ] names = new String[5];
// ArrayLists are empty to start with
ArrayList<Integer> highScoreList = new ArrayList<Integer>();
ArrayList<String> nameList = new ArrayList<String>();
Here is a comparison of how to access and change elements in arrays and ArrayLists.
Operation |
array |
ArrayList |
---|---|---|
length/size |
array.length |
list.size() |
Access |
value = array[index]; |
value = list.get(index); |
Modify |
array[index] = value; |
list.set(index,value); |
Note that the ArrayList methods add and remove do not have a simple equivalent in arrays because they actually change the size of the underlying array and move elements over.
8.2.7. Programming Challenge : Array to ArrayList¶
Rewrite the following code that uses an array to use an ArrayList instead. In the comments write why you think an ArrayList is a better data structure to use than an array for this problem.
8.2.8. Summary¶
The following ArrayList methods, including what they do and when they are used, are part of the Java Quick Reference:
int size() : Returns the number of elements in the list
boolean add(E obj) : Appends obj to end of list; returns true
void add(int index, E obj) : Insertss obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size
remove(int index) — Removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index
E get(int index) : Returns the element at position index in the list
E set(int index, E obj) : Replaces the element at position index with obj; returns the element formerly at position index