TheDeveloperBlog.com

Home | Contact Us

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

<< Back to JAVA

Java ArrayList Examples

Build up a collection of many strings or integers with the ArrayList class from java.util.ArrayList.
ArrayList. Growth occurs at all levels of life. An animal grows. A cell grows. Growth is sometimes slow but may occur at ever faster rates.
In an ArrayList we have an array that grows. It allows us to add more elements (like cells) without concern for the total size. We first initialize our data.Initialize
First example. The ArrayList is used in many programs. But in most places, it is used in a similar way: we instantiate, add elements, and access data.

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

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

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
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
Remove. With this method we delete an element. The element slot is removed and any later elements are shifted forward. We can use an index or a value argument.

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]
SubList. This returns a view of the ArrayList. We can loop over the returned List, or access its elements, using a zero-based index. So the first element in the sub-list is at index 0.

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

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
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 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
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 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
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 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
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 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
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 the rest are removed.
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]
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 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
Clear performance. With clear() we can reuse the same ArrayList many times. This reduces allocations. The cleared ArrayList can be used faster than a new one.ArrayList clear Performance
Ints, Integers. In Java an ArrayList of ints is specified with the Integer type. An Integer contains an int value. I describe some issues with int ArrayLists—like compile errors.ArrayList int, Integer
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.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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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