Home
Map
ArrayList String ExamplesBuild up a collection of many strings with the ArrayList class from java.util.ArrayList.
Java
This page was last reviewed on Nov 25, 2022.
ArrayList. In an ArrayList, we can place one string after another—we have a linear collection of strings. String is a class, so the syntax for a String ArrayList is straightforward.
ArrayList, ints
Data collection. An ArrayList allows us to add more data (such as string references) without concern for the total size. We first initialize it with data.
Initialize ArrayList
Initial example. Let us start with the add and remove methods. We invoke add() to append an element at the end of an ArrayList. And remove() erases an element at an index.
ArrayList add, insert
Info When calling remove(), the element slot is removed and any later elements are shifted forward.
Detail 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) { ArrayList<String> colors = new ArrayList<>(); colors.add("?"); colors.add("red"); colors.add("bird"); colors.add("blue"); // Remove first element. colors.remove(0); System.out.println(colors); // 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.
Detail 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.
Detail 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.
Detail 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]
File lines. We read the lines of a text file with the BufferedReader class. Then we can place these lines into an ArrayList with the add method. This caches the file in memory.
File
Remove duplicates. We can develop a method to remove duplicate Strings (or other values) from an ArrayList. Internally the method uses a HashSet.
Duplicates
Convert ArrayList, string. Sometimes programs want a single, flat string that contains elements. We can convert an ArrayList to a string with join().
Convert ArrayList, String
A summary. Ordered, linear collections are commonly needed. Programs often store elements in ArrayList instances. And this type provides diverse, powerful methods.
ArrayList clear
Collections.addAll
C#VB.NETPythonGolangJavaSwiftRust
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.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.