ArrayList in Java With Example

ArrayList in Java With Example - All we should know about ArrayList

In this post, we will see ArrayList in Java with example.

Basic points about Java ArrayList.

  • In ArrayList, we can have duplicate elements.
  • ArrayList follows the insertion order.
  • ArrayList uses indexing representation to store the elements, so we can access elements randomly.
  • We can have null as an element in ArrayList.
  • None of the methods of ArrayList are synchronized.
  • The size of ArrayList increases dynamically, the initial capacity of ArrayList is 10 when we insert the 11th element the size will become 16. The new capacity will be calculated  (initial size *3)/2 +1 i.e 16.
  • ArrayList class extends AbstractList class and implements ListSerializableCloneableIterable, and RandomAccess interface.

First Example.

package com.netsurfingzone;

import java.util.ArrayList;
import java.util.List;

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

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
		System.out.println(listObject);
	}
}

OutPut – [ram, mohan, shyam, mohan, ram]

Second Example.

package com.netsurfingzone;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		// iterator() is a method defined in List interface
		// Iterator is a interface.
		// it is reference of Iterator interface
		Iterator it = listObject.iterator();

		// it.hasNext() will check, next element is there or not if yes while
		// loop will execute.
		while (it.hasNext()) {
			// it.next() will print all element one by one
			System.out.println(it.next());
		}
	}
}

The output of the above program is –

ram
mohan
shyam
mohan
ram

Different ways to iterate ArrayList in Java.

Using Iterator.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {
		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		// iterator() is a method defined in List interface
		// Iterator is a interface.
		// it is reference of Iterator interface
		Iterator it = listObject.iterator();

		// it.hasNext() will check, next element is there or not if yes while
		// loop will execute.
		while (it.hasNext()) {
			// it.next() will print all element one by one
			System.out.println(it.next());
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Iterating ArrayList using for-each loop.


import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {
		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		for (String str : listObject) {
			System.out.println(str);
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Itearig ArrayList using for loop.

import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		for (int i = 0; i < listObject.size(); i++) {
			System.out.println(listObject.get(i));
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Iterating ArrayList using a while loop.

import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {
		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		int i = 0;
		while (listObject.size() > i) {
			System.out.println(listObject.get(i));
			i++;
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Iterating ArrayList using ListIterator.

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		ListIterator lit = listObject.listIterator();
		while (lit.hasNext()) {
			System.out.println(lit.next());
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Iterating ArrayList using Java 8 lambda expressions.


import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		listObject.forEach(stringElement -> {
			System.out.println(stringElement);
		});
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Adding different types of elements in ArrayList.

In below example, we are going to add string, integer, float, and double in ArrayList.

package com.netsurfingzone;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

		List listObject = new ArrayList();
		listObject.add("ram");
		listObject.add(2);
		listObject.add(10f);
		listObject.add(10L);

		Iterator it = listObject.iterator();
		while (it.hasNext()) {
			// it.next() will print all element one by one
			System.out.println(it.next());
		}
	}
}

Output is –

ram
2
10.0
10

How to Synchronized ArrayList in java?

ArrayList is not synchronized i.e none of the methods in ArrayList is synchronized. We can make ArrayList synchronized using predefined API,  List list = Collections.synchronizedList(List list). Let’s see an example.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		List<String> list = Collections.synchronizedList(new ArrayList(listObject));
		Iterator<String> it = listObject.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Converting ArrayList to Array and Array to ArrayList in Java.

Converting ArrayList to Array in java.

import java.util.ArrayList;
import java.util.List;

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

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		// we have toArray() defined in List interface which returns Object
		// array
		Object[] arraysObject = listObject.toArray();
		for (Object obj : arraysObject) {
			System.out.println(obj);
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram

Converting  Array and Array to ArrayList.

import java.util.Arrays;
import java.util.List;

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

		// declaration and instantiation of array
		String[] stringArray = new String[4];
		// initialization of array
		stringArray[0] = "ram";
		stringArray[1] = "mohan";
		stringArray[2] = "sohan";
		stringArray[3] = "rohan";

		// now we have to convert stringArray array into List
		// Arrays class have method called asList()
		List<String> listObjOfStringType = Arrays.asList(stringArray);
		// now we have List listObjOfStringType. let's iterate it.
		for (String str : listObjOfStringType) {
			System.out.println(str);
		}

	}
}

Output is –

ram
mohan
sohan
rohan

Let’s see a real-time scenario where and how to use these concepts. Suppose we have some method m1(Object [] objArray) with return type public List<Object>. Now inside m1(Object [] objArray), we are calling some another method m2(List listReference) which can take the only list. We want to pass objArray into m2() as an argument since m2() can have the only list as an argument it will give the compilation error if we will pass an array. We have two options here –

  • Change the method m2()  itself which can take the list. Not recommended, because it may be used in many places.
  • Change the objArray to list and pass in m2(). This makes sense. Isn’t it?

Let’s see an example that illustrates the above explanation.

import java.util.Arrays;
import java.util.List;

public class ArrayToArrayListUse {

	// first we define m2() which takes List and also returns List only
	public List<Object> m2(List listRefence) {
		List<Object> listObject = listRefence;
		return listObject;
	}
	public List<Object> m1(Object[] objArray) {

		// we have to pass this objArray in m2().
		// since m2() can have only List, we need to convert objArray to List.
		List<Object> listObj = Arrays.asList(objArray);

		// now we have listObj which we can pass in m2()
		List<Object> listObjectCameFromm2method = m2(listObj);
		return listObjectCameFromm2method;
	}

	public static void main(String[] args) {
		ArrayToArrayListUse listUse = new ArrayToArrayListUse();

		// declaration and instantiation of array
		Object[] objArray = new Object[4];

		// initialization of array
		objArray[0] = "ram";
		objArray[1] = "mohan";
		objArray[2] = "sohan";
		objArray[3] = "rohan";

		// let's call m1() which taking array and returning list
		List<Object> finalListObj = listUse.m1(objArray);
		// let's iterate it
		for (Object obj : finalListObj) {
			System.out.println(obj);
		}
	}
}

Output is –

ram
mohan
sohan
rohan

Adding user-defined class object into ArrayList.

We have seen a couple of examples where we added String and other wrapper classes. Let’s see a basic example where we will add a user-defined class in the ArrayList.

package com.netsurfingzone;
import java.util.ArrayList;
import java.util.List;

class Book {
	String bookName;
	int bookId;

	public Book(String bookName, int bookId) {
		this.bookName = bookName;
		this.bookId = bookId;
	}
}

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

		List<Book> listOfBookType = new ArrayList<>();
		Book b1 = new Book("bookname1", 10);
		Book b2 = new Book("bookname2", 13);
		Book b3 = new Book("bookname3", 11);
		Book b4 = new Book("bookname4", 9);

		listOfBookType.add(b1);
		listOfBookType.add(b2);
		listOfBookType.add(b3);
		listOfBookType.add(b4);
		for (Book b : listOfBookType) {
			System.out.println("Book name is: - " + b.bookName + "   "
					+ "Book id is :- " + b.bookId);
		}
	}
}

Output is –

Book name is: – bookname1 Book id is :- 10
Book name is: – bookname2 Book id is :- 13
Book name is: – bookname3 Book id is :- 11
Book name is: – bookname4 Book id is :- 9

Defining ArrayList as final.

Can we define List as final, if yes what will happen? Can we add more elements? Let’s see an example.

import java.util.ArrayList;
import java.util.List;

public class FinalListExample {
	public static void main(String[] args) {
		// creating object of ArrayList
		final List<String> listObjOfStringType = new ArrayList<>();

		// adding couple of elements in ArrayList
		listObjOfStringType.add("ram");
		listObjOfStringType.add("mohan");
		listObjOfStringType.add("sohan");
		listObjOfStringType.add("rohan");

		for (String str : listObjOfStringType) {
			System.out.println(str);
		}
	}
}

Output is –

ram
mohan
sohan
rohan

Yes, we can make List as final, and also we can add elements. In the above program, we have listObjOfStringType which is the reference of  List type and object of ArrayList. As we know about the final variable if we initialize once its value can’t be changed. Here we can’t change the value of listObjOfStringType but we can add some element to this. Making the ArrayList final is not stopping us to add elements. So what is the difference between the final list and the normal list? Let’s see another example.

import java.util.ArrayList;
import java.util.List;

public class FinalListExample {
	public static void main(String[] args) {
		// creating object of ArrayList
		final List<String> listObjOfStringType = new ArrayList<>();

		// adding couple of elements in ArrayList
		listObjOfStringType.add("ram");
		listObjOfStringType.add("mohan");
		listObjOfStringType.add("sohan");
		listObjOfStringType.add("rohan");

		// assigning a new value in listObjOfStringType
		listObjOfStringType = new ArrayList<>();

		for (String str : listObjOfStringType) {
			System.out.println(str);
		}
	}
}

The above program will show the compilation error.

ArrayList in Java With Example

Creating read-only ArrayList in Java.

Suppose we have created some ArrayList and added a couple of element, later we realize we have added all elements in the list, now onwards we don’t want to add more elements. We can make ArrayList read-only(we can’t perform add or remove operation with the list). Collections class provides the unmodifiableList() method to define read-only ArrayList. Let’s see an example.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReadOnlyArrayListExample {

	public static void main(String[] args) {

		// creating object of ArrayList
		List<String> listObjOfStringType = new ArrayList<>();

		// adding couple of elements in ArrayList
		listObjOfStringType.add("ram");
		listObjOfStringType.add("mohan");
		listObjOfStringType.add("sohan");
		listObjOfStringType.add("rohan");

		// iterating using for-each loop
		System.out.println("before read only list");
		for (String str : listObjOfStringType) {
			System.out.println(str);
		}
		
		// Let's make listObjOfStringType read only
		List<String> readOnlyListObject = Collections.unmodifiableList(listObjOfStringType);
		
		//adding element in readOnlyListObject 		
		readOnlyListObject.add("shyam");
		System.out.println(readOnlyListObject);						
	}
}

Output is –

before read only list
ram
mohan
sohan
rohan
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at ReadOnlyArrayListExample.main(ReadOnlyArrayListExample.java:29)

We are getting an exception, we have made ArrayList read-only, can’t add elements anymore.

Converting ArrayList into Set.

We can convert ArrayList to HashSet using HashSet constructors. Let’s see an example.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();
		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");
		Iterator<String> itObjectForList = listObject.iterator();
		while (itObjectForList.hasNext()) {
			System.out.println(itObjectForList.next());
		}

		System.out.println("After converting into set ----");
		Set<String> set = new HashSet<String>(listObject);
		Iterator<String> itObjectForSet = set.iterator();
		while (itObjectForSet.hasNext()) {
			System.out.println(itObjectForSet.next());
		}
	}
}

Output is –

ram
mohan
shyam
mohan
ram
After converting into set —-
shyam
mohan
ram

Performance in the case of ArrayList and Vector.

Here we will see how ArrayList is better than vector in performance.

package rrrr;
import java.util.*;
public class ArrayListVsVectorPerf {
public static void main(String[] args) {
	
	// define ArrayList Object
	List<String> listOfArrayList = new ArrayList<>();	
	//get current time in milliseconds
	long l1 = System.currentTimeMillis();
	for(int i=0; i<1000000; i++) {
		//add ram 1M times
		listOfArrayList.add("ram");
	}
	//get current time in milliseconds
	long l2 = System.currentTimeMillis();	
	//l2 - l1 will return time took to add 1M times ram in listOfArrayList
	System.out.println("time taken by ArrayList "+(l2-l1));
	
	long l3 = System.currentTimeMillis();
	List<String> listOfVector = new Vector<>();
	for(int i=0; i<1000000; i++) {
		listOfVector.add("ram");
	}		
	long l4 = System.currentTimeMillis();	
	//l2 - l1 will return time took to add 1M times ram in listOfVector
	System.out.println("time taken by Vector    "+(l4-l3));
	
	
}
}

Output is –

time taken by ArrayList 18
time taken by Vector 39

Run the above example multiple times. You will see ArrayList will always take less time than Vector.

Check ArrayList is empty or not in Java.

Let’s see different ways to check ArrayList is empty or not in java. The most popular way is to use Apache Commons CollectionUtil.isEmpty(). Since it checks for size and null both. If we are sure that our list can’t be null then we can go for List isEmpty(). The Apache commons provides other popular utils methods.

Using org.apache.commons.collections4.CollectionUtils isEmpty() method.

Apache Commons provides CollectionUtil.isEmpty() method to check a list is empty or not in Java. It checks for size as well null.

package com.netsurfingzone.serviceimpl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class CheckListIsEmpty {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		System.out.println(CollectionUtils.isEmpty(list));//true
		//add some element
		list.add("john");
		list.add("mark");
		System.out.println(CollectionUtils.isEmpty(list));//false
		
		list = null;
		System.out.println(CollectionUtils.isEmpty(list));//true
		
	}
}

Output is –

true
false
true

Using org.springframework.util.CollectionsUtil.isEmpty() method.

If we are working on Spring Projects then we can use org.springframework.util.CollectionsUtil.isEmpty() method to check a list is empty or not in java. It also checks for size as well as null.

package com.netsurfingzone.serviceimpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.CollectionUtils;

public class CheckListIsEmpty {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		System.out.println(CollectionUtils.isEmpty(list));// true

		// add some element
		list.add("john");
		list.add("mark");
		System.out.println(CollectionUtils.isEmpty(list));// false

		list = null;
		System.out.println(CollectionUtils.isEmpty(list));// true
	}
}

Output is –

true
false
true

Using java.util.List.isEmpty() method.

List interface also provides isEmpty() method which checks for size only. If our list is null we can’t use List’s isEmpty() method. It will throw NullPointerException.

package com.netsurfingzone.serviceimpl;

import java.util.ArrayList;
import java.util.List;


public class CheckListIsEmpty {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		System.out.println(list.isEmpty());// true

		// add some element
		list.add("john");
		list.add("mark");
		System.out.println(list.isEmpty());// false

	}
}

Output is –

true
false

Define a method to check list is empty.


package com.netsurfingzone.serviceimpl;

import java.util.ArrayList;
import java.util.List;

public class CheckListIsEmpty {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		if (isEmpty(list)) {
			System.out.println(true);
		} else {
			System.out.println(false);
		}
	}

	public static boolean isEmpty(List list) {
		if (list.size() == 0 || list == null) {
			return true;
		}
		return false;
	}
}

Output is  – true

Constructure of ArrayList in Java with Examples.

Constructors of ArrayList.

There are three constructions that have been defined in the ArrayList.

ArrayList() – Create a Arraylist using default constructor with initial capacity 10.

ArrayList(Collection<? extends E> c) – Using this constructor we can convert other collections to ArrayList. Let’s see an example where we are going to convert HashSet to ArrayList.

package com.netsurfingzone;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConvertHashSetToArrrayList {
	public static void main(String[] args) {
		Set<String> hashSetObj = new HashSet<>();
		hashSetObj.add("ram");
		hashSetObj.add("mohan");
		hashSetObj.add("sohan");
		hashSetObj.add("rohan");
		hashSetObj.add("ram");
		System.out.println("Before converting ArrayList:  " + hashSetObj);

		// Convert HashSet to ArrayList
		List<String> listObj = new ArrayList<>(hashSetObj);
		listObj.add("ram");
		System.out.println("After converting ArrayList:  " + listObj);
	}
}

Output is –

Before converting ArrayList: [sohan, rohan, mohan, ram]
After converting ArrayList: [sohan, rohan, mohan, ram, ram]

ArrayList(int initialCapacity) – Using this constructor while creating ArrayList we can define initial capacity.

package com.netsurfingzone;

import java.util.ArrayList;
import java.util.List;

public class ConvertHashSetToArrrayList {
	public static void main(String[] args) {
		List<String> listObj = new ArrayList<>(20);
		listObj.add("john");
		System.out.println(listObj);
	}
}

ArrayList methods in Java with example.

ArrayList add() method example – The add() method used to appends the specified element to the end of this list

import java.util.ArrayList;

public class AddExample {
public static void main(String[] args) {
	ArrayList<String> list =new ArrayList<>();
	list.add("kavita");
	list.add("Anita");
	list.add("Babita");
	list.add("Sunita");
	list.add("Gita");
	for(String s:list) {
		System.out.println(s);
	}
}
}

The output is :-

kavita
Anita
Babita
Sunita
Gita

ArryList add(int index, E element) method example – Inserts the specified element at the specified position in this list.

Example of add() method.

import java.util.ArrayList;

public class AddExample {
public static void main(String[] args) {
	ArrayList<String> list =new ArrayList<>();
	list.add("kavita");
	list.add("Anita");
	list.add("Babita");
	list.add("Sunita");
	list.add("Gita");
	
	for(String s:list) {
		System.out.println(s);
	}
	list.add(3,"Karan");
	System.out.println("After adding  a element in orignal list");
	for(String s:list) {
		System.out.println(s);
	}
}
}

The output is :

kavita
Anita
Babita
Sunita
Gita
After adding a element in orignal list
kavita
Anita
Babita
Karan
Sunita
Gita

ArrayList remove() method example – There are two overloaded version is defined. First one takes an int as an argument and another takes an object as an argument.

import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		System.out.println("Before remove()  " + listObject);

		// we can remove the elements at any position specifying index
		listObject.remove(0);
		System.out.println("After remove() using index based  " + listObject);

		// we can remove the elements providing elements name. 
		listObject.remove("mohan");
		System.out.println("After remove() used as object name  " + listObject);
	}
}

Output is –

Before remove() [ram, mohan, shyam, mohan, ram]
After remove() using index based [mohan, shyam, mohan, ram]
After remove() used as object name [shyam, mohan, ram]

In the output, we can see remove(“mohan”) removed only one “mohan” which was in the first place.

ArrayList removeAll() method example – It takes Collection interface as an argument, will remove all elements from the list, which we are passing as an argument.

import java.util.ArrayList;
import java.util.List;

public class ArraListExample {

	public static void main(String[] args) {

		List<String> listObject = new ArrayList<>();

		listObject.add("ram");
		listObject.add("mohan");
		listObject.add("shyam");
		listObject.add("mohan");
		listObject.add("ram");

		System.out.println("Before remove()  " + listObject);

		// we can remove all the elements from list providing
		listObject.removeAll(listObject);
		System.out.println("After removeAll()  " + listObject);
	}
}

Output is –

Before remove() [ram, mohan, shyam, mohan, ram]
After removeAll() []

ArrayList clear() method example.

The clear() method is used to remove all elements from list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListClearExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("Jon");
		list.add("Arya");
		list.add("Sansa");
		list.add("Bran");
		System.out.println("Befor clear() method---"+list);
		list.clear();
		System.out.println("After clear() method---"+list);
		
	}
}

Output:-

Before clear() method—[Jon, Arya, Sansa, Bran]
After clear() method—[]

ArrayList contains() method example – Checks list contains specifc element or not(return true or false).

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListContainsExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("Jon");
		list.add("Arya");
		list.add("Sansa");
		list.add("Bran");
		System.out.println("Using contains() method---" + list.contains("Jack"));
		System.out.println("Using contains() method---" + list.contains("Sansa"));
	}
}

Output-

Using contains() method—false
Using contains() method—true

ArrayList ensureCapacity() method example – Increase the capacity of list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListEnsureCapacityExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Jack");
		list.add("Jon");
		System.out.println(list);
		list.ensureCapacity(200);
		System.out.println("Capacity has been increased 200 for list object");
	}
}

Output –

[John, Jack, Jon]
Capacity has been increased 200 for list object

ArrayList get(int index) method example – The get() method returns the element for given elements.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListGetExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Jack");
		list.add("Jon");
		System.out.println(list.get(0));
	}
}

Outout –

John

ArrayList indexOf(Object o) method example – Returns the index of first occurence of specific element.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListIndexOfExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Jack");
		list.add("Jon");
		System.out.println("Index of John--- " + list.indexOf("John"));
	}
}

Output –

Index of John— 0

ArrayList isEmpty() method example – Used to check list contains any element or not. It returns true if list is empty and false if list is not empty.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListIndexOfExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Jack");
		list.add("Jon");
		System.out.println(list.isEmpty());
	}
}

Output is –

false

ArrayList iterator() method example – The iterator method returns an iterator over the elements in this list in proper sequence.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Jack");
		list.add("Jon");
		Iterator<String> it = list.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

ArrayList lastIndexOf(Object o) method example – It returns the index of the last occurrence of the specified element.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListLastIndexOfExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Mike");
		list.add("Mike");
		list.add("Mike");
		list.add("Mike");
		list.add("Mike");
		list.add("Mike");
		System.out.println(list.lastIndexOf("Mike"));
	}
}

Output –

8

ArrayList listIterator() method example – Returns a list iterator over the elements in this list (in proper sequence). There are two overloaded versions of listIterator() method.

listIterator()
listIterator(int index)

Example of listIterator()

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		ListIterator<String> it = list.listIterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output is –

John
Sansa
Mike

Example of listIterator(int index).

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.ListIterator;

public class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Peter");
		list.add("Steve");
		list.add("Nancy");
		list.add("Lucus");
		ListIterator<String> it = list.listIterator(3);
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}
}

Output –

Peter
Steve
Nancy
Lucus

ArrayList remove() method example – There are two overloaded version of remove() method.

E remove(int index) – Removes the element at the specified position of the given list.
boolean remove(Object o) – Removes the first occurrence of the specific element from the list.

remove(int index) example –

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Peter");
		list.add("Steve");
		list.add("Nancy");
		System.out.println("Before remove(int inex) method--- " + list);
		list.remove(0);
		System.out.println("After remove(int index) method--- " + list);

	}
}

Output –

Before remove(int inex) method— [John, Sansa, Mike, Peter, Steve, Nancy]
After remove(int index) method— [Sansa, Mike, Peter, Steve, Nancy]

remove(Object o) example –

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Peter");
		list.add("Steve");
		list.add("Nancy");
		System.out.println("Before remove(Object o) method--- " + list);
		list.remove("John");
		System.out.println("After remove(Object o) method--- " + list);

	}
}

Output –

Before remove(Object o) method— [John, Sansa, Mike, Peter, Steve, Nancy]
After remove(Object o) method— [Sansa, Mike, Peter, Steve, Nancy]

ArrayList removeAll() method example – Used to remove all elements from list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListRemoveAllExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Peter");
		list.add("Steve");
		list.add("Nancy");
		System.out.println("Before removeAll(Collection coll) method--- " + list);
		list.removeAll(list);
		System.out.println("After removeAll(Collection coll) method--- " + list);

	}
}

Output –

Before removeAll(Collection coll) method— [John, Sansa, Mike, Peter, Steve, Nancy]
After removeAll(Collection coll) method— []

ArrayList removeIf() method example Removes all of the elements of this collection that satisfy the given predicate.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListRemoveIfExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Sansa");
		list.add("Mike");
		list.add("Peter");
		list.add("Steve");
		list.add("Nancy");
		System.out.println("Before removeIf() method--- " + list);
		list.removeIf(element -> (element == "Sansa"));
		System.out.println("After removeIf() method--- " + list);

	}
}

Output –

Before removeIf() method— [John, Sansa, Mike, Peter, Steve, Nancy]
After removeIf() method— [John, Mike, Peter, Steve, Nancy]

ArrayList removeRange(int fromIndex, int toIndex) method example – Used to removes elements from list whose index is between fromIndex and toIndex. The fromIndex is inclusive and toIndex is exclusive.

ArrayList replaceAll() method example – Replaces each element of this list with the result of applying the operator to that element.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

class LowerCaseOperator implements UnaryOperator<String> {
	public String apply(String s) {
		return s.toLowerCase();
	}
}

public class ArrayListReplaceAllExample {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		System.out.println("Before replaceAll() method--- " + list);
		list.replaceAll(new LowerCaseOperator());
		System.out.println("After replaceAll() method--- " + list);

	}
}

Output –

Before replaceAll() method— [John, Mike, Lucus, Sansa]
After replaceAll() method— [john, mike, lucus, sansa]

ArrayList retainAll() method example – Retains the elements in this list that are contained in the specified collection.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListRetainAllExample {
	public static void main(String[] args) {
		List<String> list1 = new ArrayList<>();
		list1.add("John");
		list1.add("Mike");
		list1.add("Lucus");
		list1.add("Sansa");

		List<String> list2 = new ArrayList<>();
		list2.add("Tony");
		list2.add("Bob");
		list2.add("Lucus");
		list2.add("Sansa");

		System.out.println("retainAll() method example --- " + list1.retainAll(list2));

	}
}

Output –

retainAll() method example — true

ArrayList set(int index, E element) method example – Used to replace the element at the specific position in the list with the specific element.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSetExample {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		System.out.println("Before set() method---" + list);
		list.set(0, "Bob");
		System.out.println("After set() method---- " + list);

	}
}

Output –

Before set() method—[John, Mike, Lucus, Sansa]
After set() method—- [Bob, Mike, Lucus, Sansa]

ArrayList size() method example – Used to get size of list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSizeExample {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		System.out.println(list.size());
	}
}

Output –

4

ArrayList sort() method example – Used to sort the list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListSortExample {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		System.out.println("Before sorting---" + list);
		Collections.sort(list);
		System.out.println("After sorting---" + list);
	}
}

Output –

Before sorting—[John, Mike, Lucus, Sansa]
After sorting—[John, Lucus, Mike, Sansa]

ArrayList toArray() method example – Used to convert list to array.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;
import java.util.List;

public class ArrayListToArrayExample {
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		Object[] objArray = list.toArray();
		for (Object o : objArray) {
			System.out.println(o.toString());
		}
	}
}

Output –

John
Mike
Lucus
Sansa

ArrayList trimToSize() method example – Used to trm the list, capacity of list will be equal to size of list.

package com.netsurfingzone.arraylist;

import java.util.ArrayList;

public class ArrayListTrimToSizeExample {
	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<>();
		list.add("John");
		list.add("Mike");
		list.add("Lucus");
		list.add("Sansa");
		list.trimToSize();
		System.out.println("Now Capacity of list is equal to size of list--" + list);
	}
}

Output –

Now Capacity of list is equal to size of list–[John, Mike, Lucus, Sansa]

That’s all about ArrayList in Java with example.

Check other important posts related to ArrayList.

Java ArrayList docs.

Summary – We have seen about ArrayList in Java with example.