Home | 7.1 Introduction | 7.2 Methods | 7.3 Traversing | 7.4 Algorithms | 7.5 Searching | 7.6 Sorting | 7.7 Ethical Issues |
7.2 - ArrayList Methods
ArrayList Methods
7.2: ArrayList Methods
Learning Objectives
Students will be able to represent collections of related object reference data using ArrayList
objects.
Essential Knowledge
-
Iteration statements provide a means to access all the elements stored within an
ArrayList
. This process is referred to as “traversing theArrayList
.” -
The following
ArrayList
methods, including what they do and when they are used, are part of the Java Quick Reference:int size()
- Returns the count of elements within the list.boolean add(E obj)
- Appends the objectobj
to the end of the list and returnstrue
.void add(int index, E obj)
- Insertsobj
at the specifiedindex
, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list’s size by 1.E get(int index)
- Retrieves the element at the givenindex
in the list.E set(int index, E obj)
- Replaces the element at the specifiedindex
withobj
and returns the previous element at that index.E remove(int index)
- Deletes the element at the specifiedindex
, shifting all subsequent elements one index to the left, reducing the list’s size by one, and returning the removed element.
-
Java allows the generic
ArrayList<E>
, where the generic typeE
specifies the type of element. -
When
ArrayList<E>
is specified, the types of the reference parameters and return type when using the methods are typeE
. -
ArrayList<E>
is preferred overArrayList
because it allows the compiler to find errors that would otherwise be found at runtime.
Size of the ArrayList
int size();
: Returns the number of elements in the list.
Consider the following code:
ArrayList<Integer> a1 = new ArrayList<>();
System.out.println(a1.size());
0
Adding Items to an ArrayList
boolean add(E obj);
: Appendsobj
to the end of the list and returns true.void add(int index, E obj)
: Insertsobj
at positionindex
, as long asindex
is within the list’s length. It moves each element in the list 1 index higher and adds 1 to the list’s size.
Consider the following code:
ArrayList<Double> a2 = new ArrayList<>();
a2.add(1.0);
a2.add(2.0);
a2.add(3.0);
a2.add(1, 4.0);
System.out.println(a2);
[1.0, 4.0, 2.0, 3.0]
Let’s Look at an Example
Consider the following code:
ArrayList<String> h = new ArrayList<>();
h.add("Hello");
h.add("Hello");
h.add("HeLLO");
h.add("Hello");
h.add(1, "Hola");
h.add(26.2);
h.add(new String("Hello"));
h.add(false);
| h.add(26.2);
incompatible types: double cannot be converted to java.lang.String
Now, consider this code:
ArrayList<String> g = new ArrayList<>();
g.add("Hello");
g.add("Hello");
g.add("HeLLO");
g.add("Hello");
g.add(1, "Hola");
g.add(new String("Hello"));
System.out.println(g);
[Hello, Hola, Hello, HeLLO, Hello, Hello]
Question: Why does this code work?
Deleting Items from an ArrayList
E remove(int index)
: Removes the element at position index
, and moves the elements at position index + 1
and higher to the left. It also subtracts one from the list’s size. The return value is the element formerly at position index
.
// If you are confused of what list g is, look back at the previous code.
g.remove(3);
String former = g.remove(0);
System.out.println(former);
Hello
Updating Items in an ArrayList
To update variables or object properties in Java, simply assign new values using the = operator or update object fields through methods. Make sure the data types match and understand how scopes affect where updates can occur.
String car = g.set(1, "xx");
System.out.println(car);
System.out.println(g);
Hello
[Hola, xx, Hello, Hello]
Accessing Items in an ArrayList
In Java, you can access items in an array by using the index of the element, with array indices starting from 0. For example, array[0] will access the first element, and array[2] will access the third element. You can use a loop, such as a for or while loop, to iterate through all the elements of the array.
String hello = g.get(3);
System.out.println(hello);
System.out.println(g);
Hello
[Hola, xx, Hello, Hello]
Passing an ArrayList
as a Method Parameter
The only time that it is wise to use ArrayList
instead of ArrayList<E>
is when it is as a function parameter and it is only using ArrayList<>.get(E)
or ArrayList<>.size()
. Consider the following code:
private void accessOnly(ArrayList arr) {
if (arr.size() > 0) {
System.out.println(arr.get(0)); // Change the index to the one you want to access
} else {
System.out.println("Array is empty");
}
}
ArrayList<Integer> myList = new ArrayList<Integer>();
accessOnly(myList);
Array is empty
Returning an ArrayList
from a Method
In order for you to return an ArrayList
, the data type must be specified, and the return type must be the same as the return value. Consider the following code:
private ArrayList<String> returnTheSame() {
ArrayList<String> arr = new ArrayList<String>(); // Initialize the ArrayList
arr.add("Hello");
return arr;
}
ArrayList<String> result = returnTheSame();
System.out.println(result);
[Hello]
Hacks
-
The learning objective is that “Students will be able to represent collections of related object reference data using
ArrayList
objects.” What does this mean to you? -
Answer the following questions:
- Look back at Size of the
ArrayList
. What does the code output and why? - 0 because there are 0 items in the array list
- Look back at Adding items to an
ArrayList
. What does the code output and why? What type of function isvoid
, and what will be the return value? - the add() method is a void method which doesnt return anything and simply adds stuff to the array
- Look back at Example 1. What two lines did we remove? Why?
- If an
ArrayList
is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?
- Look back at Size of the
-
Using the Hack Helper, write code that will:
- Add 2 items to the list.
- Remove an item from the list anywhere of the user’s choice.
- Replace am item anywhere in the list of the user’s choice.
- Get the first and last element of the list, no matter the length.
- Return the items added, removed, replaced, and the list’s size, in one string.
Hack Helper
public class ArrayListMethodsExample {
private ArrayList<Integer> manipulateList(/* You can put parameters here if you want to... */) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(1);
return arr;
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
ArrayListMethodsExample example = new ArrayListMethodsExample();
ArrayList<Integer> output = example.manipulateList();
System.out.println(output);
}
}
| System.out.println("No students⬤
unclosed string literal
| System.out.println("No students⬤
reached end of file while parsing