Lesson 13
ArrayList
Author: Brandon Fajardo (11/10/17) Updated by Gillian VerSteeg (9/13/20)
Introduction
Review: In the last lesson, we talked about arrays.
Lesson topic: In this lesson, we will be going over ArrayLists, which are a different way to store a collection of values.
Topic 1 - ArrayList
Subtopic 1 - Definition
ArrayList: An array of objects.
An ArrayList is very similar to an array but solves many of the common problems with arrays, including:
An ArrayList automatically resizes itself when necessary
An ArrayList lets you insert objects into the middle of the collection
An ArrayList lets you delete items
A difference between arrays and ArrayLists is how ArrayLists do not use primitive data types such as int, double, char, and long. What they can hold are Strings (because they are an object) and Wrapper Classes.
Wrapper Class: A Java class that was created to hold one primitive data type. Examples are Integer, Double, Byte, and Short. Objects of these types hold one value of their corresponding primitive type (int, double, byte, short). They are used when you desire to store primitive data types in Java structures that require objects (ex: JLists, ArrayLists, JComboboxes, JTables).
Note:
Wrapper Classes are not as efficient as primitive types
Arrays have objects, while ArrayLists have objects.
Primitive Data Type
Wrapper Class
char
Character
byte
Byte
short
Short
long
Integer
float
Float
double
Double
boolean
Boolean
Subtopic 2 - Declaring
To use an ArrayList, you must first import the ArrayList Class.
import java.util.ArrayList;
To declare an ArrayList, you can use either of the following two notations:
ArrayList <data type> variable
variable = new ArrayList <data type> ();
or
ArrayList <data type> name = new ArrayList <data type> ();
Note: When declaring an ArrayList, you do not need to put a data type within the second <>.
Topic 2 - Methods
After declaring an ArrayList, then you can use the following methods:
Method
Purpose
add()
used to add objects to the ArrayList
get()
used to access an object and to refer to the index number
set()
used to modify an object and refer to the index number
remove()
used to remove an object
clear()
used to remove all of the objects in the ArrayList
size()
used to find out how many objects an ArrayList has
indexOf()
finds the index number
contains()
checks if a value is contained in the ArrayList
Subtopic 1 - add() and get()
Add() is used to add an object to the ArrayList.
Example of add():
ArrayList <String> cars = new ArrayList <String> ();
cars.add ("Volvo");
cars.add ("BMW");
cars.add ("Ford");
cars.add ("Mazda");
System.out.println(cars); //Prints out: [Volvo, BMW, Ford, Mazda]
To add objects in an ArrayList, you use the following notation:
name.add (IndexNum, variable);
Ex:
cars.add (2, "Toyota");
System.out.println(cars) //Prints: [Volvo, BMW, Toyota, Ford, Mazda]
As you can see, this assigns a new object to the index number 2, where "Ford" used to be. This does not, however, delete the object in that index, it just shifts over. Now there are five objects in the ArrayList "cars" rather than four.
Just like adding an object in an array, you also use the index number for get().
System.out.println(cars.get(1)); //Prints: [BMW]
From this example, we can see that get() was used to print only one object of the ArrayList. Get() can also be used in other settings such as mathematical equations.
Note: Remember, like arrays, ArrayLists also use indexes. Indexes always start at 0, then continue in increments of 1.
Challenge #1: How do you create a "Double" ArrayList called "numbers" with five objects in this order:
17.4
0.12
98.001
34.7
8
Then use get() to print 3 things:
Multiply the second number by the third,
Add the fifth number to the fires then divide by 2.
Get the modulus of the fourth number divided by the second.
Answer:
ArrayList <Double> numbers = new ArrayList <Double> ();
numbers.add (17.4);
numbers.add (0.12);
numbers.add (98.001);
numbers.add (34.7);
numbers.add (8.0);
System.out.println(numbers.get(1)*numbers.get(2)); //Prints 11.76012
System.out.println((numbers.get(0)+numbers.get(4))/2); //Prints 12.7
System.out.println(numbers.get(3)%numbers.get(1)); //Prints 0.020000000000004126
Subtopic 2 - set()
set() is used to modify an object by referring to its index number.
Notation:
name.set(indexNum, value);
Example:
ArrayList <Integer> digits_of_pi = new ArrayList <Integer> ();
digits_of_pi.add(3);
digits_of_pi.add(1);
digits_of_pi.add(4);
digits_of_pi.add(1);
digits_of_pi.add(5);
digits_of_pi.add(9);
digits_of_pi.add(3); //Supposed to be 2
digits_of_pi.add(6);
digits_of_pi.add(5);
digits_of_pi.add(3);
System.out.println(digits_of_pi); //Prints [3,1,4,1,5,9,3,6,5,3]
digits_of_pi.set (6,2);
System.out.println(digits_of_pi); //Prints: [3,1,4,1,5,9,2,6,5,3]
Subtopic 3 - remove()
When you remove an index, it does not become empty. Rather, all of the indexes after it move down a number.
There are two ways to remove an index:
name.remove(index);
//or
name.remove(object value);
The only way the second notation works is if the "object value" is exactly the same. Otherwise, nothing will be removed.
Example:
ArrayList <String> MCHS_Motto = new ArrayList <String>();
MCHS_Motto.add("Be Someone");
MCHS_Motto.add("Go Somewhere");
MCHS_Motto.add("Have a Sandwich");
MCHS_Motto.add("Seek Excellence");
System.out.println(MCHS_Motto); //Prints [Be someone, Go Somewhwere, Have a Sandwich, Seek Excellence]
MCHS_Motto.remove(2); //Removes "Have a Sandwich"
System.out.println(MCHS_Motto); //Prints [Be someone, Go Somewhere, Seek Excellence)
//or
MCHS_Motto.remove("Have A Sandwich");
System.out.println(MCHS_Motto); //Prints [Be someone, Go Somewhwere, Have a Sandwich, Seek Excellence]
// This did not remove the third statement because the 'A' was capitalized.
Subtopic 4 - size() and clear()
size() is used to find the size of an ArrayList.
Notation:
name.size();
Example:
ArrayList <String> poem = new ArrayList <String> ();
poem.add("Haikus");
poem.add("are");
poem.add("easy");
poem.add("but");
poem.add("sometimes");
poem.add("they");
poem.add("don't");
poem.add("make");
poem.add("sense.");
poem.add("Toaster");
System.out.println(poem);
System.out.println(poem.size()); //prints 10 objects
Note: When using size(), the variable you will receive does NOT count indexes. Rather, it counts the number of objects.
clear() is used to remove all objects of an ArrayList.
poem.clear();
System.out.println(poem); // prints "[]" because "poem" is empty
Even though you clear an array, it is still there. If you want to use it later, you do not need to rename it.
poem.add (0, "The world is so full of a number of things,");
poem.add (1, "I'm sure we should all be as happy as kings.");
System.out.println(poem);
Topic 3 - Printing ArrayLists
Subtopic 1 - Using a Loop
There are different ways to print ArrayLists besides using "System.out.println." One of these ways is to use a loop. When using a loop, the output will look like a list of variables, with one object per line.
Ex:
ArrayList <String> videoGames = new ArrayList <String> ();
videoGames.add("Minecraft");
videoGames.add("Candy Crush");
videoGames.add("Flappy Bird");
videoGames.add("The Legend of Zelda");
for (int i = 0; i < videoGames.size(); i++){
System.out.println(videoGames.get(i);
}
/*
Prints:
Minecraft
Candy Crust
Flappy Bird
The Legend of Zelda
*/
Subtopic 2 - Using an Iterator
Iterator: Spits out a collection's values, one after another.
To obtain values from a collection using an iterator, you must use next().
To find out whether the iterator has any more values, you use hasNext().
When using an Iterator, this allows a person to print out each of the objects in one continuous line rather than separated by commas within [ ].
Ex:
import java.util.Iterator;
ArrayList <String> bookTitle = new ArrayList <String> ();
bookTitle.add("The");
bookTitle.add("Adventures");
bookTitle.add("of");
bookTitle.add("Huckleberry");
bookTitle.add("Finn");
bookTitle.add("by");
bookTitle.add("Mark");
bookTitle.add("Twain");
System.out.println(bookTitle);
//Prints [The, Adventures, of, Huckelberry, Finn, by, Mark, Twain]
Iterator <String> iter = bookTitle.iterator();
while (iter.hasNext()){
System.out.print(iter.next() + " ");
}
// Prints: The Adventures of Huckleberry Finn by Mark Twain
Note:
Remember to import java.util.Iterator;
To use an iterator correctly, remember to use System.out.print instead of System.out.println.
Topic 4 - The "Collections" Class
The Collections class, which uses "import java.util.Collections;" sorts an ArrayList either alphabetically or numerically, depending on the data type. It uses the sort() method.
Ex:
import java.util.Collections;
ArrayList <Integer> years = new ArrayList <Integer>();
years.add(1215);
years.add(1492);
years.add(2020);
years.add(2004);
years.add(1348);
years.add(1201);
System.out.println(years);
//Prints [1215, 1492, 2020, 2004, 1348, 1201]
Collections.sort(years);
System.out.println(years);
//Prints [1201, 1215, 1348, 1492, 2004, 2020]
reverseOrder() is used to print a list in reverse order. It works just like sort(), but in reverse.
Collections.sort(yeras, Collections.reverseOrder());
System.out.println(years);
//Prints [2020, 2004, 1492, 1348, 1215, 1201]
Ex:
ArrayList <String> countrySingers = new ArrayLIst <Stirng> ();
countrySingers.add("Tim McGraw");
countrySingers.add("Luke Bryan");
countrySingers.add("Keith Urban");
countrySingers.add("Blake Shelton");
Collections.sort(countrySingers);
for (String i : countrySingers){
System.out.println (i);
}
//Prints in alphabetical order
Collections.sort(countrySingers, Colections.reverseOrder());
System.out.println(countrySingers);
//Prints in reverse alphabetical order
Note: When you sort an ArrayList, it does not return to the original index.
Topic 5 - Copying ArrayLists
Shallow Copy: Only the object references are copied. Uses clone(). Deep Copy: Creates an exact copy of all the fields and references.

Simple Example of Copying:
ArrayList <Double> mouse = new ArrayList <> ();
mouse.add(3.7);
mouse.add(8.31);
mouse.add(17.1);
mouse.add(5.555);
System.out.println(mouse); //Prints the numbers above
ArrayList <Double> mouseClone = (ArrayList<Double>)
mouse.clone();
System.out.println(mouseClone); //Prints the same as "mouse"
mouse.set (0, 19.2);
System.out.println(mouse); // Changes
System.out.println(mouseClone); // Does not change
mouseClone.remove(3);
System.out.println(mouse); // Stays the same
System.out.println(mouseClone); // Changes
A "Deep" copy is much more complicated than a Shallow copy. For more information about copying ArrayLists, please see https://howtodoinjava.com/java/collections/arraylist/arraylist-clone-deep-copy/.
Conclusion
Recap: In this lesson, we covered ArrayLists and their methods. We also examined different ways to print ArrayLists and to copy them.
Next: This was the last lesson! Congratulations! Read the next note for some final statements
Last updated
Was this helpful?