Chapter 10: ArrayLists
In the last chapter, you learned about arrays. One of the biggest limitations of arrays is their fixed size. A work around was discussed for expanding arrays by creating a new array and copying the old array values into the new. In this chapter, you will learn about ArrayLists. The ArrayList class is used to make dynamic resizable lists of non-primitive objects. They work very similarly to arrays, but you don't have to worry about fixed lengths. ArrayLists automatically expand if they need more space.
ArrayLists, like arrays, may sort large collections of same-type objects using indices. The first index of an ArrayList starts at zero, just like an array.
ArrayLists are not as efficient as arrays. When they are resized, they expand in the same way arrays were expanded in the previous chapter. If you do not need your arrays to be dynamic, you will be better off just using regular arrays.
Using an ArrayList
To use an ArrayList, it must first be imported from the java.util
package.
import java.util.ArrayList; //import ArrayList
ArrayLists are instantiated just like any other object in Java. You declare the reference variable and instantiate a new ArrayList with the new keyword. One thing to note here is the generic parameter, indicated with less than/greater than signs (sometimes called angle brackets). The generic parameter allows you to specify what object type the ArrayList is made of.
ArrayList<E> myArrayList = new ArrayList<E>(); //create a new ArrayList, where E is the object type we want to use.
Primitive Wrapper Classes
Because ArrayLists cannot be made using primitive types, if you want to create an array of doubles, you must use a primitive object wrapper. A primitive wrapper class "wraps" the primitive type in an object. The primitive wrapper class for a double is the Double class.
The code sample below shows how to make an array of doubles, compared to an ArrayList of doubles.
//an array of doubles
double myArray[] = new double[5];
//an ArrayList of Doubles
ArrayList<Double> myArrayList = new ArrayList<Double>();
Adding Values
In order to add values to an ArrayList, we have to use the ArrayList.add()
method. The argument of the add method is the object being added to the ArrayList.
Suppose you want to add the Double values of 5.0, 9.5, 10.1, and 4.4 to myArrayList. In order to do this, you will have to instantiate new Double objects and give them values, before adding them to the ArrayList.
//Create the ArrayList of Doubles
ArrayList<Double> myArrayList = new ArrayList<Double>();
//Adding 4 Doubles to myArrayList
myArrayList.add(5.0);
myArrayList.add(9.5);
myArrayList.add(10.1);
myArrayList.add(4.4);
Every time the .add method is called, a new element of the ArrayList is created. The argument in the add method is the object being added to the ArrayList.
Accessing Data
To access each element of an ArrayList, you can use the ArrayList.get(idx)
method. The argument in the get method is the index of the ArrayList we want to access.
If I print out the first index of the ArrayList using the .get method, it would look like this:
//print out the first value
System.out.println(myArrayList.get(0));
5.0
If you want to print out all the values of an ArrayList, you can just print out the ArrayList itself.
System.out.println(myArrayList);
[5.0, 9.5, 10.1, 4.4]
The ArrayList class has a built in toString() method that adds the objects to a list and outputs the results. This differs from regular arrays, where you must loop through the values to print them all out.
If you wanted to print out all the values in an ArrayList using a loop, you could do so like this:
//print all the values
for(int i = 0; i < myArrayList.size(); i++){
System.out.println(myArrayList.get(i));
}
5.0 9.5 10.1 4.4
In the above code, the ArrayList.size()
method is the functional equivalent of the .length variable for an array. The size() method returns the length of the ArrayList as an integer.
Removing Elements
In addition to dynamically adding/expanding the ArrayList, you can also remove elements from an ArrayList at any time by calling the ArrayList.remove(idx)
method, where idx is the index of the ArrayList you want to remove.
//ArrayList removal example
myArrayList.remove(2);
System.out.println(myArrayList);
[5.0, 9.5, 4.4]
The above code removed the second index of the ArrayList and printed the results. Since the indicies start at zero, this removes the third element in the ArrayList, the value 10.1.
You may also remove an object from an ArrayList by calling the remove method and passing along the object to remove.
//removing the value 9.5 from the ArrayList
myArrayList.remove(9.5);
System.out.println(myArrayList);
[5.0, 10.1, 4.4]
If multiples of the same object exist in an ArrayList, the .remove method will only remove the first instance of that value.
//values
myArrayList.add(5.0);
myArrayList.add(9.5);
myArrayList.add(10.1);
myArrayList.add(4.4);
myArrayList.add(9.5);
myArrayList.add(9.5);
//only removes first 9.5 at index 1
myArrayList.remove(9.5);
//test print
System.out.println(myArrayList);
[5.0, 10.1, 4.4, 9.5, 9.5]
The two 9.5s added at the end remain, and only the first one was removed.
Collections
ArrayLists are a type of Collection. The Collections class has a number of useful methods we can use with ArrayLists.
Sort
In the previous chapter, you learned how to sort an array from least to greatest manually. The Collections.sort(list)
method enables you to automatically sort a collection. Different objects may be compared using different criteria. The Double class compares by less than and greater than.
To use Collections, it must be imported from the utilities package.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
//Create ArrayList
ArrayList<Double> myArrayList = new ArrayList<Double>();
//Add some Doubles
myArrayList.add(34.0);
myArrayList.add(54.30);
myArrayList.add(43.3);
myArrayList.add(0.05);
myArrayList.add(3231.32);
myArrayList.add(-64.2);
//Sort it using Collections.sort
Collections.sort(myArrayList);
//Print the result
System.out.println(myArrayList);
}
}
[-64.2, 0.05, 34.0, 43.3, 54.3, 3231.32]
The ArrayList was automatically sorted from least to greatest using Collections.sort. I just provided myArrayList as an argument, and it was sorted. No need to manually sort doubles.
Reverse
If you want to sort from greatest to least, you can sort the list and then reverse it using the Collections.reverse(list)
method.
Collections.sort(myArrayList);
Collections.reverse(myArrayList);
[3231.32, 54.3, 43.3, 34.0, 0.05, -64.2]
Min/Max
To find the minimum or maximum value in a Collection, you may use the Collections.min(list)
and Collections.max(list)
methods.
Double max = Collections.max(myArrayList);
Double min = Collections.min(myArrayList);
//Print the result
System.out.println("The max is: " + max);
System.out.println("The min is: " + min);
The max is: 3231.32 The min is: -64.2
Shuffle
The Collections.shuffle(list)
method randomly shuffles the collection.
Collections.shuffle(myArrayList);
System.out.println(myArrayList);
Each time I run the program, the ArrayList will be sorted differently. Here's what my first run looked like:
[43.3, 0.05, 34.0, 3231.32, -64.2, 54.3]
Second run:
[3231.32, 43.3, 54.3, -64.2, 34.0, 0.05]
Other Types
You can easily create an ArrayList of any type of object. Just change the type accordingly. Here's an example with Strings.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
//Create ArrayList
ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");
System.out.println(myList);
}
}
[Hello, World]
Other Useful Methods
isEmpty
The isEmpty()
method returns a boolean value of true or false if an ArrayList is empty.
size
The size()
method returns the size of an ArrayList as an integer. This may be useful if you need to iterate through the list.
The example below is a method that takes an ArrayList of type Double as a parameter. It prints the average of the values in the list or prints out a message if there's nothing in the list.
printAverage Method public static void printAverage(ArrayList<Double> list){
if(list.isEmpty()){
System.out.println("The list is empty.");
}
else{
Double sum = 0.0;
for(int i = 0; i < list.size(); i++){
sum += list.get(i);
}
Double average = sum / list.size();
System.out.println("The average of the given ArrayList values is: " + average);
}
}
Test Code
public static void main(String[] args) {
ArrayList<Double> myList = new ArrayList<Double>();
myList.add(5.5);
myList.add(4.3);
myList.add(23.2);
printAverage(myList);
ArrayList<Double> anotherList = new ArrayList<Double>();
printAverage(anotherList);
}
The average of the given ArrayList values is: 11.0 The list is empty.
Assignment: Number Counter
There is no "shorthand" syntax for assigning multiple values to an ArrayList like there is for Arrays. However, you may use the Arrays class to create a new List of items, and add this list to an ArrayList. The sample code below creates an ArrayList of Integers and adds 25 integers to it.
Directions: Write an algorithm that loops through each item in this ArrayList and counts the total number of 5s in the list. Do this programmatically (use a loop, don't just hardcode the answer).
Starter Codeimport java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.addAll(Arrays.asList(4, 6, 7, 2, 5, 2, 1, 6, 4, 7, 5, 5, 9, 0, 1, 0, 5, 4, 5, 3, 1, 0, 5, 0, 5));
//TODO: Loop through myList and count amount of '5' in list
}
}
I have counted 7 fives.View Solution Chapter 11: Multidimensional Arrays
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.addAll(Arrays.asList(4, 6, 7, 2, 5, 2, 1, 6, 4, 7, 5, 5, 9, 0, 1, 0, 5, 4, 5, 3, 1, 0, 5, 0, 5));
//keep track of the number of fives
int count = 0;
//loop through myList
for(int i = 0; i < myList.size(); i++){
if (myList.get(i).equals(5)){
//increment the counter
count ++;
}
}
//print the result
System.out.println("I have counted " + count + " fives in the list.");
}
}