7.1: ArrayList Intro
- ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size
- Instead of creating a new array of a different size and copying the data from the initial array to the new one, we can use ArrayLists
Arrays | ArrayLists |
---|---|
Fixed Length | Resizable Length |
Fundamental Java feature | Part of a framework |
An object with no methods | Class with many methods |
Not as flexible | Designed to be very flexible |
Can store primitive data | Not designed to store primitives |
Slightly slower than arrays | |
Need an import statement |
In order to use the ArrayList class, the ArrayList class needs to be imported from the java util package. This can be done by writing import java.util.ArrayList at the top of the class file.
import java.util.ArrayList; // Import the ArrayList class
// Declare and initialize an ArrayList of integers
ArrayList<Integer> numbersList = new ArrayList<>();
ArrayList objects are created in the same fashion as other object classes. The primary difference with ArrayLists is that the element type of the ArrayList must be specified using angled bracket <>. In this example, E represents the data type that will be used in the ArrayList. This can be replaced by an object data type:
ArrayList<String> list = new ArrayList<String>();
We can actually declare ArrayLists without specifying the type that will be included in the ArrayList, but specifying the data type is smarter because it allows the compiler to find errors before run time, so its more efficient and easy to spot errors.
ArrayList list = new ArrayList();
Quick lil popcorn hack
Create 2 ArrayLists, 1 called studentName
and 1 called studentAge
public class Student
{
public static void main(String[] args)
{
//Initialize your ArrayLists
}
}
7.2: ArrayList Methods
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());
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);
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);
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);
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);
Updating Items in an ArrayList
E set(int index, E obj)
: Replaces the element at position index
with obj
and returns the element formerly at position index
.
String helloFormer = g.set(1, "Bonjour");
System.out.println(helloFormer);
System.out.println(g);
Accessing Items in an ArrayList
E get(int index)
Returns the element at position index
in the list.
String hello = g.get(3);
System.out.println(hello);
System.out.println(g);
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);
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);
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? - 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? - 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 String manipulateList(/* You can put parameters here if you want to... */) {
// Your code here
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
ArrayListMethodsExample example = new ArrayListMethodsExample();
String output = example.manipulateList();
System.out.println(output);
}
}
7.4: Developing Algorithms Using ArrayLists
Learning Objectives
In the context of ArrayList
objects, this module aims to teach the following skills:
a. Iterating through ArrayLists
using for
or while
loops.
b. Iterating through ArrayLists
using enhanced for
loops.
In the realm of algorithms, within the context of specific requirements that demand the utilization of ArrayList
traversals, students will be able to:
- Recognize established algorithms.
- Customize existing algorithms.
- Create new algorithms.
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 methods related to
ArrayLists
, their functions, and appropriate use are covered in 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.
-
There exist established algorithms for
ArrayLists
that make use of traversals to:- Insert elements.
- Remove elements.
- Apply the same algorithms commonly used with 1D arrays.
Popcorn Hacks:
Before you uncomment the code and run it, guess what the code will do based on what you’ve learned.
Let’s Look at an Example (Example 1)
public class ArrayListExample {
private double findMax(double[] values) {
// double max = values[0];
//for (int index = 1; index < values.length; index++) {
// if (values[index] > max) {
// max = values[index];
// }
//}
// return max;
}
public static void main(String[] args) {
double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 69.0, 2.0, 4.0, 6.0, 2.0, 5.0, 10.0};
ArrayListExample example = new ArrayListExample();
double max = example.findMax(nums);
System.out.println("Maximum value: " + max);
}
}
ArrayListExample.main(null);
Take a closer look at the findMax()
method. It takes in a list of doubles as parameters. It will then use a for
loop to find the maximum value in the list. Now, using what we know, can we replace the list of doubles with an ArrayList of Doubles? We sure can! Take a look at how we can use ArrayList to do just that:
public class ArrayListExample {
private double findMax(ArrayList<Double> values) {
// double max = values.get(0);
//for (int index = 1; index < values.size(); index++) {
// if (values.get(index) > max) {
// max = values.get(index);
// }
//}
//return max;
}
public static void main(String[] args) {
ArrayList<Double> nums = new ArrayList<>();
nums.add(1.0);
nums.add(3.0);
nums.add(2.0);
nums.add(2.0);
nums.add(1.0);
nums.add(69.0);
nums.add(2.0);
nums.add(4.0);
nums.add(6.0);
nums.add(2.0);
nums.add(5.0);
nums.add(10.0);
ArrayListExample example = new ArrayListExample();
double max = example.findMax(nums);
System.out.println("Maximum value: " + max);
}
}
ArrayListExample.main(null);
Let’s Look at an Example (Example 2)
Take a look at this code:
public class ArrayListExample {
private int findMin(int[] values) {
//int min = Integer.MAX_VALUE;
//for (int currentValue : values) {
// if (currentValue < min) {
// min = currentValue;
// }
//}
return min;
}
public static void main(String[] args) {
int[] nums = {420, 703, 2034, 582, 1047, 4545};
ArrayListExample example = new ArrayListExample();
int min = example.findMin(nums);
System.out.println("Minimum value: " + min);
}
}
ArrayListExample.main(null);
Now, can we use ArrayLists to make this code better? We sure can! Take a look at the new and improved code that uses ArrayLists:
public class ArrayListExample {
private int findMin(ArrayList<Integer> values) {
//int min = Integer.MAX_VALUE;
//for (int currentValue : values) {
// if (currentValue < min) {
// min = currentValue;
// }
//}
return min;
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add(420);
nums.add(703);
nums.add(2034);
nums.add(582);
nums.add(1047);
nums.add(4545);
ArrayListExample example = new ArrayListExample();
int min = example.findMin(nums);
System.out.println("Minimum value: " + min);
}
}
ArrayListExample.main(null);
Hacks
- Answer the questions:
- Look back at the examples. What’s similar? What’s different?
- Why do we use
ArrayList
? Why not just regular lists?
- Demonstrate at least two
ArrayList
methods that aren’tArrayList<>.size()
andArrayList<>.get()
. - Write the method
findSum()
using the Hack Helper and incorporatingArrayList
.
Hack Helper
public class ArrayListHacks {
private int findSum(ArrayList<Integer> values) {
// Your code here
return 0;
}
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.add(0);
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(5);
nums.add(8);
ArrayListHacks hacks = new ArrayListHacks();
hacks.findSum(nums);
}
}
ArrayListHacks.main(null);