TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Java ArrayList Examples

This Java article uses the ArrayList class. ArrayList is a resizable, ordered collection of elements.

ArrayList. Programs handle uncertain data.

An ArrayList accommodates extra elements, more than we might anticipate. This capability is useful.

Dynamic resizing. ArrayList runs efficiently, resizes internally, makes many programs simpler. In Java we can specify the type of elements (a class).

Create. This example creates an ArrayList. It uses diamond inference syntax on the right side. The <> characters are inferred from the left. The type is integer.

Size: We call the size() method on the ArrayList instance. This returns the number of elements in the collection.

Get: Finally we invoke the get() method, which receives the index of the element to get. We loop over each index. We repeatedly call get.

Based on:

Java 7

Java program that uses ArrayList

import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

	// Create new ArrayList.
	ArrayList<Integer> elements = new ArrayList<>();

	// Add three elements.
	elements.add(10);
	elements.add(15);
	elements.add(20);

	// Get size and display.
	int count = elements.size();
	System.out.println("Count: " + count);

	// 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

For-loop. We can use a simpler syntax to loop over elements. We use the colon instead of an iteration variable. This improves readability. But it reduces flexibility in the loop.

Tip: In most program contexts, the simplest loop possible is preferable. It is best to avoid unnecessary iteration variables.

For

Java 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

IndexOf. We use the indexOf and lastIndexOf methods to find indexes. IndexOf searches from the beginning. LastIndexOf searches from the end.

Here: The ArrayList contains two elements with the value 100. IndexOf finds the first one. LastIndexOf finds the second.

Caution: When using indexOf() and lastIndexOf() it is important to test for -1. Exceptions may occur if we omit this test.

Exceptions

Java program that uses indexOf, lastIndexOf

import java.util.ArrayList;

public class Program {
    public static void main(String[] args) {

	ArrayList<Integer> list = new ArrayList<>();
	list.add(101);
	list.add(100);
	list.add(99);
	list.add(100);
	list.add(99);

	// Search for values.
	int index = list.indexOf(100);
	int lastIndex = list.lastIndexOf(100);
	int notFound = list.indexOf(200);

	// Display results.
	System.out.println(index);     // 1
	System.out.println(lastIndex); // 3
	System.out.println(notFound);  // -1
    }
}

Output

1
3
-1

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.

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

Clear, isEmpty. An empty ArrayList has no elements. When we call clear() on an ArrayList, it will become empty. This method is useful when we want to reuse an existing ArrayList.

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

SubList. This returns a view of the ArrayList. We pass the subList method two arguments: the first index and the last index of the view we want to use. This view is returned as a List.

Loop: We can loop over the sub-list, or access its elements, using a zero-based index. So the first element in the sub-list is at index 0.

Set: 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 five 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

ToArray. The toArray method copies an ArrayList's elements to an array. It has two versions—one returns an Object array and requires casting. This version, though, returns a typed array.

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 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

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: I define an addCats method that receives an ArrayList. This method allocates no new objects.

Instead: The addCats method operates on an existing ArrayList. In a complex program, reusing an ArrayList is often a performance win.

Java 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

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.

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 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

Collections.min, max. Many static methods in the Collections class can be used on an ArrayList. Here we use two simple ones: min and max.

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 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

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.

In-place: Collections.sort operates in-place. The original collection is modified and no value is returned.

Sort: Collections.sort

Java 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

Collections.addAll. With this we add many elements to an ArrayList at once. The second argument is either an array of the elements to add, or those elements as arguments.

Collections.addAll

Here: We add three elements from an array to an ArrayList. We then add two more elements with addAll.

Java 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

Static field. Often programs need a global store of data. A global or static ArrayList can help. This may cause problems with many threads, but for simple programs it works well.

Tip: As a public static field, the ArrayList can be used in any method, without the need to pass it around as an argument.

Static

Tip 2: An ArrayList also works as an instance field. This is better if separate collections are required.

Java 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

Vector. This is an older Java collection with behavior similar to ArrayList. It has been updated over the years to have modern syntax. Vector is thread-safe, but this reduces speed.

Vector

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.

BufferedReader: Read Lines

Remove duplicates. We can develop a method to remove duplicate Strings (or other values) from an ArrayList. Internally the method uses a HashSet.

Remove 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

Ordered, linear collections are commonly needed. Programs often store elements in ArrayList instances. And this type provides diverse, powerful methods.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf