Java ArrayList Tutorial with Examples

ArrayList is a Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.

This class provides methods to manipulate the size of the array that is used internally to store the list.

(This class is roughly equivalent to Vector , except that it is unsynchronized.)

The underlying data structure is resizable array (or) growable array.

Duplicate objects are allowed.

Insertion order preserved.

Heterogeneous objects are allowed.(except TreeSet , TreeMap every where heterogenious objects are allowed).

Null insertion is possible.

Constructors:
1) ArrayList a=new ArrayList();

Creates an empty ArrayList object with default initial capacity "10" if ArrayList reaches its max capacity then a new ArrayList object will be created with
New capacity=(current capacity*3/2)+1

2) ArrayList a=new ArrayList(int initialcapacity);

Creates an empty ArrayList object with the specified initial capacity.

3) ArrayList a=new ArrayList(collection c);

Creates an equivalent ArrayList object for the given Collection that is this constructor meant for inter conversation between collection objects.,
That is to dance between collection objects.

package com.javacodestuffs.core.collections.arrayList; import java.util.*; class ArrayListDemo { public static void main(String[] args) { ArrayList a=new ArrayList(); a.add("A"); a.add(10); a.add("A"); a.add(null); System.out.println(a);//[A, 10, A, null] a.remove(2); System.out.println(a);//[A, 10, null] a.add(2,"m"); a.add("n"); System.out.println(a);//[A, 10, m, null, n] } } output: [A, 10, A, null] [A, 10, null] [A, 10, m, null, n]

Usually, we can use the collection to hold and transfer objects from one tier to another tier. To provide support for this requirement every Collection class already implements Serializable and Cloneable interfaces.

ArrayList and Vector classes implement the RandomAccess interface so that any random element we can access at the same speed. Hence ArrayList is the best choice of "retrieval operation".

RandomAccess interface present in the util package and doesn't contain any methods. It is a marker interface.

ArrayList a1=new ArrayList(); LinkedList a2=new LinkedList(); System.out.println(a1 instanceof Serializable ); //true System.out.println(a2 instanceof Clonable); //true System.out.println(a1 instanceof RandomAccess); //true System.out.println(a2 instanceof RandomAccess); //false

The synchronized version of ArrayList

Collections class defines the following method to return the synchronized version of List.

public static List synchronizedList(list l);

The following example shows the synchronized version of the previous example. The output of the program is always the same due to synchronization.

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SynchronizedArrayList { public static void main(String[] args) throws InterruptedException { List safeList = Collections.synchronizedList(new ArrayList < >()); safeList.add(1); safeList.add(2); safeList.add(3); // Thread pool of size 10 ExecutorService executorService = Executors.newFixedThreadPool(5); // Create a Runnable task that increments each element of the ArrayList by one Runnable task = () - >{ incrementArrayList(safeList); }; // Submit the task to the executor service 500 times. // All the tasks will modify the ArrayList concurrently for (int i = 0; i < 500; i++) { executorService.submit(task); } executorService.shutdown(); executorService.awaitTermination(45, TimeUnit.SECONDS); System.out.println(safeList); } // Increment all the values in the ArrayList private static void incrementArrayList(List < Integer > safeList) { synchronized(safeList) { for (int i = 0; i < safeList.size(); i++) { Integer value = safeList.get(i); safeList.set(i, value + 1); } } } } output: [501, 502, 503]

Similarly, we can get a synchronized version of Set and Map objects by using the following methods.

public static Set synchronizedSet(Set s); public static Map synchronizedMap(Map m);

ArrayList is the best choice if our frequent operation is retrieval.

ArrayList is the worst choice if our frequent operation is insertion (or) deletion in the middle because it requires several internal shift operations.

Creating an ArrayList from another collection

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.List; public class ArrayListFromCollection { public static void main(String[] args) { List numberlist1 = new ArrayList < >(); numberlist1.add(2); numberlist1.add(4); numberlist1.add(6); numberlist1.add(10); numberlist1.add(14); System.out.println("numberlist1 is: "); System.out.println(numberlist1); List numberlist = new ArrayList <>(numberlist1); List numberlist2 = new ArrayList <>(); numberlist2.add(34); numberlist2.add(54); numberlist2.add(66); numberlist2.add(44); numberlist2.add(88); System.out.println("\nnumberlist2 is: "); System.out.println(numberlist2); numberlist.addAll(numberlist2); System.out.println("\nnumberlist is: "); System.out.println(numberlist); } } output: numberlist1 is: [2, 4, 6, 10, 14] numberlist2 is: [34, 54, 66, 44, 88] numberlist is: [2, 4, 6, 10, 14, 34, 54, 66, 44, 88]

Accessing elements from an ArrayList

Check ArrayList is empty

Find the size of an ArrayList

Access the element at a particular index in an ArrayList

Modify the element at a particular index in an ArrayList

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.List; public class ArrayListOperations { public static void main(String[] args) { List langList = new ArrayList < >(); // Check ArrayList is empty System.out.println("Language list empty is empty : " + langList.isEmpty()); langList.add("Java"); langList.add("Php"); langList.add(".Net"); langList.add("Node"); langList.add("Python"); langList.add("Angular"); langList.add("Go"); langList.add("Scala"); langList.add("Groovy"); // Get size of an ArrayList System.out.println("\nList of Programming languages"); System.out.println(langList); // Get the element from given index String first = langList.get(0); String second = langList.get(1); String last = langList.get(langList.size() - 1); System.out.println("\nBest Company: " + first); System.out.println("Second Best Company: " + second); System.out.println("Last Language in the list: " + last); // Modify the element at given index langList.set(5, "C++"); System.out.println("\nModified list: " + langList); } } output: Language list empty is empty : true List of Programming languages [Java, Php, .Net, Node, Python, Angular, Go, Scala, Groovy] Best Company: Java Second Best Company: Php Last Language in the list: Groovy Modified list: [Java, Php, .Net, Node, Python, C++, Go, Scala, Groovy]

Iterating over an ArrayList

The following example shows how to iterate over an ArrayList using

Java 8 forEach and lambda expression. iterator(). iterator() and Java 8 forEachRemaining() method. listIterator(). Simple for-each loop. for loop with index.

package com.javacodestuffs.core.collections.arrayList; import java.util.List; import java.util.ListIterator; import java.util.ArrayList; import java.util.Iterator; public class IterateArrayListExample { public static void main(String[] args) { List < String > fruitsList = new ArrayList < >(); fruitsList.add("Mango"); fruitsList.add("Apple"); fruitsList.add("Banana"); fruitsList.add("BlackBerry"); fruitsList.add("DragonFruits"); fruitsList.add("Coconut"); System.out.println("\n::::::::: Using an iterator() :::::::::"); Iterator < String > fruitsListIterator = fruitsList.iterator(); while (fruitsListIterator.hasNext()) { String fruit = fruitsListIterator.next(); System.out.println(fruit); } System.out.println("::::::::: Using Java 8 forEach and lambda :::::::::"); fruitsList.forEach(fruit - >{ System.out.println(fruit); }); System.out.println("\n::::::::: Using an iterator() and Java 8 forEachRemaining() method :::::::::"); fruitsListIterator = fruitsList.iterator(); fruitsListIterator.forEachRemaining(fruit - >{ System.out.println(fruit); }); System.out.println("\n::::::::: Using simple for-each loop :::::::::"); for (String fruit: fruitsList) { System.out.println(fruit); } System.out.println("\n::::::::: Using a listIterator() to traverse in both directions :::::::::"); // Here, we start from the end of the list and traverse backwards. ListIterator < String > fruitsListIterator1 = fruitsList.listIterator(fruitsList.size()); while (fruitsListIterator1.hasPrevious()) { String fruit = fruitsListIterator1.previous(); System.out.println(fruit); } System.out.println("\n::::::::: Using for loop with index :::::::::"); for (int i = 0; i < fruitsList.size(); i++) { System.out.println(fruitsList.get(i)); } } } output: ::::::::: Using an iterator() ::::::::: Mango Apple Banana BlackBerry DragonFruits Coconut ::::::::: Using Java 8 forEach and lambda ::::::::: Mango Apple Banana BlackBerry DragonFruits Coconut ::::::::: Using an iterator() and Java 8 forEachRemaining() method ::::::::: Mango Apple Banana BlackBerry DragonFruits Coconut ::::::::: Using simple for-each loop ::::::::: Mango Apple Banana BlackBerry DragonFruits Coconut ::::::::: Using a listIterator() to traverse in both directions ::::::::: Coconut DragonFruits BlackBerry Banana Apple Mango ::::::::: Using for loop with index ::::::::: Mango Apple Banana BlackBerry DragonFruits Coconut

Searching for elements in an ArrayList

The example below shows how to:

Check if an ArrayList contains a given element

Find the index of the first occurrence of an element in an ArrayList

Find the index of the last occurrence of an element in an ArrayList

package com.javacodestuffs.core.collections.arrayList; import java.util.List; import java.util.ArrayList; public class SearchElementsInArrayList { public static void main(String[] args) { List < String > names = new ArrayList < >(); names.add("Anuradha"); names.add("Revati"); names.add("Bhoomi"); names.add("Vishnu"); names.add("Borish"); names.add("Anna"); names.add("Abhijit"); // Check if an ArrayList contains an element System.out.println("Names list contain \"Bhoomi\"? : " + names.contains("Bhoomi")); //index of the first occurrence of an element in an ArrayList System.out.println("\nindexOf \"Revati\": " + names.indexOf("Revati")); System.out.println("indexOf \"Anuradha\": " + names.indexOf("Anuradha")); System.out.println("indexOf \"Anna\": " + names.indexOf("Anna")); //last occurrence of an element in an ArrayList System.out.println("\nlastIndexOf \"Abhijit\" : " + names.lastIndexOf("Abhijit")); System.out.println("lastIndexOf \"Revati\" : " + names.lastIndexOf("Revati")); } } output: Names list contain "Bhoomi"? : true indexOf "Revati": 1 indexOf "Anuradha": 0 indexOf "Anna": 5 lastIndexOf "Abhijit" : 6 lastIndexOf "Revati" : 1

ArrayList of user-defined objects

You can create an ArrayList of any type,as arraylist support generics. It can be of simple types like Integer, String, Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user-defined objects. In the following example, you’ll learn how to create an ArrayList of user-defined objects.

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Employee { private String name; private Integer age; private Double salary; public Employee(String name, Integer age, Double salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } } public class CustomArrayListExample { public static void main(String[] args) { List < Employee > emplist = new ArrayList < >(); emplist.add(new Employee("Anuradha", 29, 75000.00)); emplist.add(new Employee("Revati", 32, 90000.00)); emplist.add(new Employee("Purva", 33, 89000.00)); emplist.add(new Employee("Abhijit", 25, 30000.00)); emplist.add(new Employee("Vishnu", 28, 60000.00)); System.out.println("EmployeeList : "); emplist.forEach(emp - >{ System.out.println(emp.toString()); }); } } output: EmployeeList : {name='Anuradha', age=29, salary=75000.0} {name='Revati', age=32, salary=90000.0} {name='Purva', age=33, salary=89000.0} {name='Abhijit', age=25, salary=30000.0} {name='Vishnu', age=28, salary=60000.0}

Sorting an ArrayList

Sorting an ArrayList is a very common task that you will encounter in your programs. In following example we will see,
Sort an ArrayList using Collections.sort() method. Sort an ArrayList using ArrayList.sort() method. Sort an ArrayList of user defined objects with a custom comparator.

1). Sort an ArrayList using Collections.sort() method

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListCollectionsSort { public static void main(String[] args) { List numbers = new ArrayList < >(); numbers.add(99); numbers.add(7); numbers.add( - 2); numbers.add(0); numbers.add(21); numbers.add(17); numbers.add(75); System.out.println("Initial list : " + numbers); Collections.sort(numbers); System.out.println("\nSorted List : " + numbers); } } output: Initial list : [99, 7, -2, 0, 21, 17, 75] Sorted List : [-2, 0, 7, 17, 21, 75, 99]

2). Sort an ArrayList using ArrayList.sort() method
package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ArrayListSort { public static void main(String[] args) { List < String > names = new ArrayList < >(); names.add("Anuradha"); names.add("Revati"); names.add("Abhijit"); names.add("Vishnu"); names.add("Anna"); names.add("Purva"); System.out.println("Unsorted Names : "); System.out.println(names); // Sort an ArrayList using sort() method names.sort(new Comparator < String > () {@Override public int compare(String name1, String name2) { return name1.compareTo(name2); } }); // The above `sort()` method call can also be written simply using lambda expression names.sort((name1, name2) - >name1.compareTo(name2)); names.sort(Comparator.naturalOrder()); System.out.println("\nSorted Names : "); System.out.println(names); } } output: Unsorted Names : [Anuradha, Revati, Abhijit, Vishnu, Anna, Purva] Sorted Names : [Abhijit, Anna, Anuradha, Purva, Revati, Vishnu]

3). Sort an ArrayList of Objects using custom Comparator

package com.javacodestuffs.core.collections.arrayList; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Employee { private String name; private Integer age; private Double salary; public Employee(String name, Integer age, Double salary) { this.name = name; this.age = age; this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", age=" + age + ", salary=" + salary + '}'; } } public class ArrayListSortExample { public static void main(String[] args) { List < Employee > employee = new ArrayList < >(); employee.add(new Employee("Anuradha", 29, 75000.00)); employee.add(new Employee("Revati", 32, 90000.00)); employee.add(new Employee("Purva", 33, 89000.00)); employee.add(new Employee("Abhijit", 25, 30000.00)); employee.add(new Employee("Vishnu", 28, 60000.00)); System.out.println("EmployeeList : "); System.out.println(employee); // Sort Employee by Age employee.sort((employee1, employee2) - >{ return employee1.getAge() - employee2.getAge(); }); employee.sort(Comparator.comparingInt(Employee::getAge)); System.out.println("\nSorted EmployeeList by Age : " + employee); // Using Collections.sort() method by passing the custom Comparator Collections.sort(employee, Comparator.comparing(Employee::getName)); System.out.println("\nSorted Employee by Name : " + employee); } } output: EmployeeList : [{name='Anuradha', age=29, salary=75000.0}, {name='Revati', age=32, salary=90000.0}, {name='Purva', age=33, salary=89000.0}, {name='Abhijit', age=25, salary=30000.0}, {name='Vishnu', age=28, salary=60000.0}] Sorted EmployeeList by Age : [{name='Abhijit', age=25, salary=30000.0}, {name='Vishnu', age=28, salary=60000.0}, {name='Anuradha', age=29, salary=75000.0}, {name='Revati', age=32, salary=90000.0}, {name='Purva', age=33, salary=89000.0}] Sorted Employee by Name : [{name='Abhijit', age=25, salary=30000.0}, {name='Anuradha', age=29, salary=75000.0}, {name='Purva', age=33, salary=89000.0}, {name='Revati', age=32, salary=90000.0}, {name='Vishnu', age=28, salary=60000.0}]

Post/Questions related to Java ArrayList

How to store values in arraylist in java?
How to return an arraylist in java?
How to print an arraylist in java?
How to display objects in arraylist in java?
How to create a table using arraylist in java?
How to find sum of elements in arraylist in java?
How to implement an arraylist in java?
How to add elements in arraylist in java?

In this article, we have seen the Java ArrayList Tutorial with Examples. All source code in the article can be found in the GitHub repository.