Home
Java
ArrayList Examples
This page was last reviewed on Feb 2, 2024.
Dot Net Perls
ArrayList. The ArrayList in Java is a linear collection of same-typed elements. It handles allocations on its own, so we do not need to resize it to add more elements.
For strings, the ArrayList can be used with straightforward style. But for ints, some complexity is introduced. To use ArrayList, we first initialize it with data.
ArrayList Initialize
ArrayList int
Initial example. When we create an ArrayList, we can omit the element type, and use var to reference the ArrayList. Sometimes it is better to specify the types however.
var
Part 1 We invoke add() to append an element at the end of an ArrayList. We add 4 Strings.
ArrayList add, addAll
Part 2 When calling remove(), the element slot is removed and any later elements are shifted forward.
Part 3 If we pass a value, remove() searches for the first occurrence and removes that element. This is slower than using an index.
import java.util.ArrayList; public class Program { public static void main(String[] args) { var colors = new ArrayList<>(); colors.add("?"); colors.add("red"); colors.add("bird"); colors.add("blue"); // Part 2: remove first element. colors.remove(0); System.out.println(colors); // Part 3: remove element with value of bird. colors.remove("bird"); System.out.println(colors); } }
[red, bird, blue] [red, blue]
Set element. To assign to a position, we use set. The index must be valid. The ArrayList must already contain a reference at the index. When set() succeeds, the new element is stored.
Note We cannot use the same syntax as an array to set an element. We must instead use get() or set() to access elements at indexes.
import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create an ArrayList. ArrayList<String> list = new ArrayList<>(); list.add("Venus"); // [0] list.add("Mars"); // [1] list.add("Earth"); // [2] // Set index 0 to a new String. list.set(0, "Saturn"); for (String value : list) { System.out.println(value); } } }
Saturn Mars Earth
Method argument. An ArrayList can be passed as an argument to another method. This modifies an ArrayList in many places without copying. We can share one ArrayList among many methods.
Here We define the addCats() method. It receives an ArrayList. This method allocates no new objects.
Info The addCats method operates on an existing ArrayList. In a complex program, reusing an ArrayList is often a performance win.
import java.util.ArrayList; public class Program { static void addCats(ArrayList<String> list) { list.add("Fluffy"); list.add("Max"); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); // Call method and pass ArrayList as argument. addCats(list); for (String value : list) { System.out.println(value); } } }
Fluffy Max
Custom class elements. An ArrayList can use built-in types like Strings or Integers. But we can also place user-defined classes in one. Here I create a Philosopher class and use it.
And In the for-loop, we display all the Philosopher objects. The System.out.println method internally uses toString.
Tip With ArrayLists and object references in classes, we construct complex models for programs.
import java.util.ArrayList; class Philosopher { public int value; public String name; public Philosopher(int value, String name) { this.value = value; this.name = name; } public String toString() { return "value = " + this.value + ", name = " + this.name; } } public class Program { public static void main(String[] args) { // Create an ArrayList of objects. ArrayList<Philosopher> list = new ArrayList<>(); list.add(new Philosopher(1, "Socrates")); list.add(new Philosopher(2, "Plato")); // Display our objects. for (Philosopher p : list) { System.out.println(p); } } }
value = 1, name = Socrates value = 2, name = Plato
Collections.sort. We can sort an ArrayList with this method. We first import java.util.Collections into our program. This method sorts in ascending (low to high) order.
Tip Collections.sort operates in-place. The original collection is modified and no value is returned.
sort
import java.util.Collections; import java.util.ArrayList; public class Program { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("cat"); list.add("bird"); list.add("ant"); list.add("dog"); // Sort the elements alphabetically. Collections.sort(list); for (String value : list) { System.out.println(value); } } }
ant bird cat dog
RetainAll. Suppose you have an ArrayList, and want to keep (or retain) only certain elements in it. With retainAll we can specify a list of elements to keep. All there stare removed.
import java.util.ArrayList; public class Program { public static void main(String[] args) { ArrayList<String> values = new ArrayList<>(); values.add("bird"); values.add("bird"); values.add("frog"); values.add("fish"); values.add("elephant"); values.add("elephant"); System.out.println(":::VALUES::: " + values); // Add elements we want to keep here. ArrayList<String> retains = new ArrayList<>(); retains.add("frog"); retains.add("elephant"); System.out.println(":::RETAINS::: " + retains); // Remove all elements not in the "retains" collection. values.retainAll(retains); System.out.println(":::AFTER RETAINALL::: " + values); } }
:::VALUES::: [bird, bird, frog, fish, elephant, elephant] :::RETAINS::: [frog, elephant] :::AFTER RETAINALL::: [frog, elephant, elephant]
Summary. Linear collections are commonly needed in Java programs. Programs often store elements in ArrayList instances. And this type provides diverse, powerful methods.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 2, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.