C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: We create an ArrayList. Diamond inference syntax is on the right side. The <> characters are inferred to mean Integer.
Part 2: Next we can call add() with one argument—this appends to the end of the ArrayList.
ArrayList add, insertPart 3: We call size(). This returns the number of elements in the collection (here it is 3).
Part 4: We loop over each index with for, and call get. Finally we invoke get(), which receives the index of the element to access.
Java program that uses ArrayList
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Part 1: create new ArrayList.
ArrayList<Integer> elements = new ArrayList<>();
// Part 2: add 3 elements.
elements.add(10);
elements.add(15);
elements.add(20);
// Part 3: get size and display.
int count = elements.size();
System.out.println("Count: " + count);
// Part 4: loop through elements.
for (int i = 0; i < elements.size(); i++) {
int value = elements.get(i);
System.out.println("Element: " + value);
}
}
}
Output
Count: 3
Element: 10
Element: 15
Element: 20
Tip: In most program contexts, the simplest loop possible is preferable. It is best to avoid unnecessary iteration variables.
ForJava program that loops over ArrayList
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Create ArrayList and add three Integers.
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
// Display values.
for (int value : list) {
System.out.println(value);
}
}
}
Output
10
20
30
Part 1: We create an ArrayList and add 5 elements. It contains 2 elements with the value 100.
Part 2: We search for values. IndexOf and lastIndexOf find different indexes because they search in different ways.
Part 3: We display the results. We see that when a value is not found, the special index -1 is returned.
Java program that uses indexOf, lastIndexOf
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Part 1: create ArrayList.
ArrayList<Integer> list = new ArrayList<>();
list.add(101);
list.add(100);
list.add(99);
list.add(100);
list.add(99);
// Part 2: search for values.
int index = list.indexOf(100);
int lastIndex = list.lastIndexOf(100);
int notFound = list.indexOf(200);
// Part 3: display results.
System.out.println("INDEX: " + index);
System.out.println("LASTINDEX: " + lastIndex);
System.out.println("NOTFOUND: " + notFound);
}
}
Output
INDEX: 1
LASTINDEX: 3
NOTFOUND: -1
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.
Java program that uses set
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);
}
}
}
Output
Saturn
Mars
Earth
IsEmpty: This method returns true if the ArrayList has zero elements. It is equivalent to testing size() >0 in an expression.
Java program that uses clear, isEmpty
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Create a new ArrayList.
ArrayList<Integer> list = new ArrayList<>();
// Add one element.
list.add(1);
// This prints false: it is not empty.
System.out.println(list.isEmpty());
// Clear ArrayList.
list.clear();
// It is now empty.
if (list.isEmpty()) {
System.out.println("Empty");
}
}
}
Output
false
Empty
Value: If we pass a value, remove() searches for the first occurrence and removes that element. This is slower than using an index.
Java program that uses remove
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);
}
}
Output
[red, bird, blue]
[red, blue]
Argument 1: The first argument to subList() is the first index of the range we want to access from the ArrayList.
Argument 2: This is the last index (not a count) of the view we want to access from the source ArrayList.
Tip: If we set() an element in the sub-list to a value, this is reflected in the original list. The indexes are automatically translated.
Java program that uses subList
import java.util.ArrayList;
import java.util.List;
public class Program {
public static void main(String[] args) {
// ... Add 5 integers to an ArrayList.
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
// ... Get sub list from 1 to 3.
List<Integer> sub = list.subList(1, 3);
// ... Display sub list.
for (int value : sub) {
System.out.println(value);
}
// ... Set the first element in "sub" to -1.
// This is reflected in the original ArrayList.
sub.set(0, -1);
System.out.println(list.get(1));
}
}
Output
10
15
-1
Tip: The toArray method will allocate a new array and return its reference unless it receives a large enough array.
So: We use toArray by passing it an empty array of the matching type. It then returns a correctly-sized array.
Java program that uses toArray
import java.util.ArrayList;
import java.util.List;
public class Program {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(7);
list.add(8);
list.add(9);
// Create an empty array and pass to toArray.
Integer[] array = {};
array = list.toArray(array);
// Our array now has the ArrayList's elements.
for (int elem : array) {
System.out.println(elem);
}
}
}
Output
7
8
9
AddCats: 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.
Java program that uses method, ArrayList
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);
}
}
}
Output
Fluffy
Max
ToString: 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.
Java program that uses objects, ArrayList
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);
}
}
}
Output
value = 1, name = Socrates
value = 2, name = Plato
Min: This scans the entire collection (an ArrayList) and returns the value of the smallest element.
Max: This returns the highest value in the collection. No loop syntax is needed.
Java program that uses Collections.min, max
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
// Create ArrayList.
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(1);
list.add(100);
list.add(5);
// Min and max.
int minimum = Collections.min(list);
int maximum = Collections.max(list);
System.out.println(minimum);
System.out.println(maximum);
}
}
Output
1
100
In-place: Collections.sort operates in-place. The original collection is modified and no value is returned.
Sort: Collections.sortJava program that uses Collections.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);
}
}
}
Output
ant
bird
cat
dog
Here: We add 3 elements from an array to an ArrayList. We then add 2 more elements with addAll.
Java program that uses Collections.addAll
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
ArrayList<Integer> values = new ArrayList<>();
Integer[] array = { 10, 20, 30 };
// Add all elements in array to ArrayList.
Collections.addAll(values, array);
// Display.
for (int value : values) {
System.out.print(value);
System.out.print(" ");
}
System.out.println();
// Add more elements.
Collections.addAll(values, 40, 50);
// Display.
for (int value : values) {
System.out.print(value);
System.out.print(" ");
}
}
}
Output
10 20 30
10 20 30 40 50
Java program that retains elements
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);
}
}
Output
:::VALUES::: [bird, bird, frog, fish, elephant, elephant]
:::RETAINS::: [frog, elephant]
:::AFTER RETAINALL::: [frog, elephant, elephant]
Tip: As a public static field, the ArrayList can be used in any method, without the need to pass it around as an argument.
StaticTip 2: An ArrayList also works as an instance field. This is better if separate collections are required.
Java program that uses static ArrayList
import java.util.ArrayList;
public class Program {
static ArrayList<Integer> values = new ArrayList<>();
public static void main(String[] args) {
// Use static ArrayList.
values.add(10);
values.add(100);
System.out.println(values.size());
// Use static ArrayList in another method.
addMore();
System.out.println(values.size());
}
static void addMore() {
values.add(1000);
}
}
Output
2
3