What method is used to remove all the items in an ArrayList control?

Remove an Element from ArrayList in Java

ArrayList is similar to the array whose size can be modified. The ArrayList class is available in the Java.util package and extends the List interface. Adding and removing an element from the ArrayList is very easy by using its built-in methods add() and remove(). However, there is more than one way of removing an element from the ArrayList that are as follows:

  1. Using ArrayList.remove() Method
    1. By index.
    2. By element
  2. Using Iterator.remove() Method
  3. Using ArrayList.removeIf() Method
What method is used to remove all the items in an ArrayList control?

All these three ways are best in their own, and can be used in some different scenario. Let's understand all these three ways, one by one.

ArrayList removeAll() method in Java with Examples

The removeAll() method of java.util.ArrayList class is used to remove from this list all of its elements that are contained in the specified collection.
Syntax:

public boolean removeAll(Collection c)

Parameters: This method takes collection c as a parameter containing elements to be removed from this list.
Returns Value: This method returns true if this list changed as a result of the call.
Exception: This method throws NullPointerException if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.
Below are the examples to illustrate the removeAll() method.
Example 1:




// Java program to demonstrate
// removeAll() method for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist1 = new ArrayList();
// Populating arrlist1
arrlist1.add(1);
arrlist1.add(2);
arrlist1.add(3);
arrlist1.add(4);
arrlist1.add(5);
// print arrlist1
System.out.println("ArrayList before "
+ "removeAll() operation : "
+ arrlist1);
// Creating another object of ArrayList
ArrayList
arrlist2 = new ArrayList();
arrlist2.add(1);
arrlist2.add(2);
arrlist2.add(3);
// print arrlist2
System.out.println("Collection Elements"
+ " to be removed : "
+ arrlist2);
// Removing elements from arrlist
// specified in arrlist2
// using removeAll() method
arrlist1.removeAll(arrlist2);
// print arrlist1
System.out.println("ArrayList after "
+ "removeAll() operation : "
+ arrlist1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output: ArrayList before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : [1, 2, 3] ArrayList after removeAll() operation : [4, 5]

Example 2: For NullPointerException




// Java program to demonstrate
// removeAll() method for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// Creating object of ArrayList
ArrayList
arrlist1 = new ArrayList();
// Populating arrlist1
arrlist1.add(1);
arrlist1.add(2);
arrlist1.add(3);
arrlist1.add(4);
arrlist1.add(5);
// print arrlist1
System.out.println("ArrayList before "
+ "removeAll() operation : "
+ arrlist1);
// Creating another object of ArrayList
ArrayList
arrlist2 = null;
// print arrlist2
System.out.println("Collection Elements"
+ " to be removed : "
+ arrlist2);
System.out.println("\nTrying to pass "
+ "null as a specified element\n");
// Removing elements from arrlist
// specified in arrlist2
// using removeAll() method
arrlist1.removeAll(arrlist2);
// print arrlist1
System.out.println("ArrayList after "
+ "removeAll() operation : "
+ arrlist1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}

Output:

ArrayList before removeAll() operation : [1, 2, 3, 4, 5] Collection Elements to be removed : null Trying to pass null as a specified elelemnt Exception thrown : java.lang.NullPointerException

What method is used to remove all the items in an ArrayList control?




Article Tags :
Java
Java - util package
Java-ArrayList
Java-Collections
Java-Functions
Practice Tags :
Java
Java-Collections

How to empty an ArrayList in Java? Example

Here is a complete Java program to remove all elements and make an ArrayList empty in Java. This program demonstrates how you can remove all elements from a given ArrayList by using both theclear() and removeAll() methods. If you want to remove just a single element then you can use the remove() method as discussed here.

The program prints all objects of ArrayList before and after calling the clear() and removeAll() method to show that method is actually working and the ArrayList is empty afterward.

You can reuse the ArrayList by clearing it but make sure you don't do that in a multi-threading environment e.g. one thread is calling the clear() method while another thread is calling the add() method to insert elements. The ArrayList class is not thread-safe and sharing the same ArrayList between multiple threads will crate thread-safety-related problems and erroneous results.

See Core Java for the Impatient to learn more about the problems of using ArrayList in muti-threading applications.

What method is used to remove all the items in an ArrayList control?




Java Program to make an ArrayList empty

Here is our complete Java program to demonstrate how to remove all elements from a give ArrayList in Java using the removeAll method.

import java.util.ArrayList; /* * Java Program to remove all elements of ArrayList. * This is also known as emptying an AraryList */ public class Main { public static void main(String[] args) { System.out.println("Welcome to Java Program to empty an ArrayList"); ArrayList listOfInsurance = new ArrayList<>(); listOfInsurance.add("Car Insurnace"); listOfInsurance.add("Health Insurnace"); listOfInsurance.add("Life Insurance"); listOfInsurance.add("Home Furniture Insurance"); listOfInsurance.add("Home loan Insurance"); System.out.println("ArrayList before emptying: "); System.out.println(listOfInsurance); // Emptying an ArrayList in Java listOfInsurance.clear(); System.out.println("ArrayList after emptying: "); System.out.println(listOfInsurance); ArrayList listOfLoans = new ArrayList<>(); listOfLoans.add("Car loan"); listOfLoans.add("Persona loan"); listOfLoans.add("Balance transfer"); listOfLoans.add("Home loan"); System.out.println("ArrayList before removing all elements: "); System.out.println(listOfLoans); // Emptying an ArrayList in Java listOfLoans.removeAll(listOfLoans); System.out.println("ArrayList after removing all elements: "); System.out.println(listOfLoans); } } Output Welcome to Java Program to empty an ArrayList ArrayList before emptying: [Car Insurnace, Health Insurnace, Life Insurance, Home Furniture Insurance, Home loan Insurance] ArrayList after emptying: [] ArrayList before removing all elements: [Car loan, Persona loan, Balance transfer, Home loan] ArrayList after removing all elements: []
You can see that both the ArrayLists are empty after calling the clear() and removeAll() methods. So it's working!!

That's all about how to remove all elements from an ArrayList in Java. As I said, clear() takes less time than removeAll() to remove all objects, hence you should always use clear() to make an ArrayList empty. But, if you are not removing all elements and a list of elements to be removed are provided to you in a Collection or List then use the removeAll() method.

Other Java ArrayList tutorials for Java Programmers
  • How to loop over ArrayList in Java? (answer)
  • How to create and initialize the ArrayList in one line? (answer)
  • How to sort an ArrayList in Java? (answer)
  • How to convert an ArrayList to String in Java? (example)
  • How to remove duplicates from ArrayList in Java? (example)
  • How to reverse an ArrayList in Java? (solution)
  • How to get the first and last element of ArrayList in Java? (solution)
  • How to declare ArrayList with values in Java? (example)
  • How to get a range of elements as sublists from ArrayList in Java? (example)
  • How convert ArrayList to HashSet in Java? (example)


Code Example To Remove Elements from ArrayList

Let's test the above theory with a simple code example of ArrayList with Integers. The following program has an ArrayList of Integers containing 1, 2, and 3 i.e. [1, 2, 3], which corresponds exactly to the index.

package test; import java.util.ArrayList; import java.util.List; /** * * @author http://java67.blogspot.com */ public class JavaTutorial{ /** * @param args the command line arguments */ public static void main(String[] args) { List numbers = new ArrayList(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("ArrayList contains : " + numbers); // Calling remove(index) numbers.remove(1); //removing object at index 1 i.e. 2nd Object, which is 2 //Calling remove(object) numbers.remove(3); } } Output: ArrayList contains : [1, 2, 3] Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2 at java.util.ArrayList.rangeCheck(ArrayList.java:635) at java.util.ArrayList.remove(ArrayList.java:474) at test.Test.main(Test.java:33) Java Result: 1
You can see that the second call is also treated as remove(index). The best way to remove ambiguity is to take out autoboxing and provide an actual object, as shown below.

System.out.println("ArrayList Before : " + numbers); // Calling remove(index) numbers.remove(1); //removing object at index 1 i.e. 2nd Object, which is 2 //Calling remove(object) numbers.remove(new Integer(3)); System.out.println("ArrayList After : " + numbers); Output : ArrayList Before : [1, 2, 3] ArrayList After : [1]
This time, it works, but I am afraid of lazy developers like me, which take autoboxing for granted. Now let's take a look at removing the object from ArrayList while Iterating over them. You must be familiar with Iterator in Java, before proceeding further.



Remove Object From ArrayList using Iterator

What method is used to remove all the items in an ArrayList control?
This is actually a subtle detail of Java programming, not obvious for first-timers, as the compiler will not complain, even if you use theremove() method from java.util.ArrayList, while using Iterator.


You will only realize your mistake, when you see ConcurrentModificationException, which itself is misleading and you may spend countless hours finding another thread, which is modifying that ArrayList, because of Concurrent word. Let's see an example.

public static void main(String[] args) { List numbers = new ArrayList(); numbers.add(101); numbers.add(200); numbers.add(301); numbers.add(400); System.out.println("ArrayList Before : " + numbers); Iterator itr = numbers.iterator(); // remove all even numbers while (itr.hasNext()) { Integer number = itr.next(); if (number % 2 == 0) { numbers.remove(number); } } System.out.println("ArrayList After : " + numbers); } Output : ArrayList Before : [101, 200, 301, 400] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at Testing.main(Testing.java:28)
You can ConcurrentModificationException, due to call to remove() method from ArrayList. This is easy in simple examples like this, but in a real project, it can be really tough. Now, to fix this exception, just replace the call of numbers.remove() to itr.remove(), this will remove the current object you are Iterating, as shown below :

System.out.println("ArrayList Before : " + numbers); Iterator itr = numbers.iterator(); // remove all even numbers while (itr.hasNext()) { Integer number = itr.next(); if (number % 2 == 0) { itr.remove(); } } System.out.println("ArrayList After : " + numbers); Output ArrayList Before : [101, 200, 301, 400] ArrayList After : [101, 301]
That’s all on this post about How to remove objects from ArrayList in Java. We have learned two ways to remove an object or element from ArrayList. By the way, You should always use remove(index) to delete objects, if you are not iterating, otherwise, always use Iterator's remove() method for removing objects from ArrayList.

By the way, the above tips will work with any index-based List implementation.

Java ArrayList.removeAll() Method

Last update on February 26 2020 08:07:31 (UTC/GMT +8 hours)

public boolean removeAll(Collection c)

The removeAll() method is used to remove all the elements from a list that are contained in the specified collection.

Package: java.util

Java Platform: Java SE 8

Syntax:

removeAll(Collection c)

Parameters:

NameDescription
ccollection containing elements to be removed from this list

Return Value:
true if this list changed as a result of the call

Throws:

  • ClassCastException - if the class of an element of this list is incompatible with the specified collection (optional)
  • NullPointerException - if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null

Pictorial presentation of ArrayList.removeAll() Method

What method is used to remove all the items in an ArrayList control?

Example: ArrayList.removeAll() Method

The following example the removeAll() method is used to remove all the elements from a list that are contained in the specified collection.

import java.util.*; public class test { public static void main(String[] args) { // create an empty array list ArrayList color_list = new ArrayList(); // use add() method to add values in the list color_list.add("White"); color_list.add("Black"); color_list.add("Red"); // create an empty array sample with an initial capacity ArrayList sample = new ArrayList(); // use add() method to add values in the list sample.add("Green"); sample.add("Red"); sample.add("White"); // remove all elements from second list if it exists in first list sample.removeAll(color_list); System.out.println("First List :"+ color_list); System.out.println("Second List :"+ sample); } }

Output:

F:\java>javac test.java F:\java>java test First List :[White, Black, Red] Second List :[Green]

Previous:removeRange Method
Next:retainAll Method



Share this Tutorial / Exercise on : Facebook and Twitter

  • New Content published on w3resource:
  • HTML-CSS Practical: Exercises, Practice, Solution
  • Java Regular Expression: Exercises, Practice, Solution
  • Scala Programming Exercises, Practice, Solution
  • Python Itertools exercises
  • Python Numpy exercises
  • Python GeoPy Package exercises
  • Python Pandas exercises
  • Python nltk exercises
  • Python BeautifulSoup exercises
  • Form Template
  • Composer - PHP Package Manager
  • PHPUnit - PHP Testing
  • Laravel - PHP Framework
  • Angular - JavaScript Framework
  • Vue - JavaScript Framework
  • Jest - JavaScript Testing Framework


Java.util.ArrayList.remove() Method


Advertisements

Previous Page
Next Page

ArrayList Methods In Java

The following table lists all the methods that are provided by the ArrayList class.

MethodMethod PrototypeMethod Description
Addboolean add(E e)Adds given element e to the end of the list.
void add(int index, E element)Adds given element ‘element’ at the specified position ‘index’.
AddAllboolean addAll (Collection extends E> c)Adds all the elements in the given collection c to the end of the list.
boolean addAll (int index, Collection extends E> c)Adds all the elements in the given collection c at the position specified by the ‘index’ in the list.
Clearvoid clear()Clears the list by removing all the elements from the list.
CloneObject clone()Makes a shallow copy of the given ArrayList.
Containsboolean contains(Object o)Checks if the list contains the given element ‘o’. Returns true if the element is present.
ensureCapacityvoid ensureCapacity (int minCapacity)Increases the capacity of the ArrayList to ensure it has the minCapacity.
GetE get(int index)Returns the element in the list present at the position specified by ‘index’.
indexOfint indexOf(Object o)Returns the index of the first occurrence of element o in the list. -1 if element o is not present in the list.
isEmptyboolean isEmpty()Checks if the given list is empty.
IteratorIterator iterator()Returns an iterator to traverse over the list elements in the proper sequence.
lastIndexOfint lastIndexOf(Object o)Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.
listIteratorListIterator listIterator()Returns list iterator to traverse over the elements of the given list.
ListIterator listIterator(int index)Returns the list iterator starting from the specified position ‘index’ to traverse over the elements of the given list.
removeE remove(int index)Deletes element at the ‘index’ in the ArrayList.
boolean remove(Object o)Deletes the first occurrence of element o from the list.
removeAllboolean removeAll(Collection c)Removes all the elements from the list that match the elements in given collection c.
removeRangeprotected void removeRange (int fromIndex, int toIndex)Removes elements specified in the given range, fromIndex (inclusive) to toIndex (exclusive) from the list.
retainAllboolean retainAll(Collection c)Retains those elements in the list that match the elements in the given collection c.
setE set(int index, E element)Sets the element value at given ‘index’ to the new value given by ‘element’.
sizeint size()Returns the total number of elements or length of the list.
subListList subList(int fromIndex, int toIndex)Returns a subList between given range, fromIndex to toIndex for the given list.
toArrayObject[] toArray()Converts the given list into an array.
T[] toArray(T[] a)Converts the given list into an array of the type given by a.
trimToSizevoid trimToSize()Trims the ArrayList capacity to the size or number of elements present in the list.

Next, we will discuss each of these methods from the ArrayList function API in detail and present programming examples. After discussing all the methods listed above, we will also take up some specific operations that are carried out using ArrayLists which are not a part of the ArrayList function API.

ArrayList add

I

Prototype: boolean add (E e)
Parameters: e=> Element to be added to the ArrayList.
Return Value: true=> Element successfully added.
Description: Adds the given element e to the end of the list.

II.

Prototype: void add (int index, E element)

Parameters:

index=> Position at which the element is to be added.
Element=> Element to be added to the ArrayList.

Return Value: void

Description: Adds given element ‘element’ at the specified position ‘index’ by shifting the element at that position and subsequent elements to the right.

Exceptions: IndexOutOfBoundsException => If the specified index is out of the range.

ArrayList addAll

I

Prototype: boolean addAll (Collection c)
Parameters: c=> Collection whose elements are to be added to the ArrayList.
Return Value: true=> If the operation has altered the ArrayList.

Description: Adds all the elements in the given collection c to the end of the list. The result of the operation is undefined if the collection is altered when the operation is in progress.

Exceptions: NullPointerException => If given collection c is null.

II

Prototype: boolean addAll (int index, Collection c)
Parameters: index=> Position at which the elements in the given collection are to be added.
Return Value: true=> If the list has changed as a result of the operation.

Description: Adds all the elements in the given collection c at the position specified by the ‘index’ in the list. The element at the specified index and subsequent elements are shifted to the right. The result of the operation is undefined if the collection being added is altered when the operation is in progress.

Exceptions: IndexOutOfBoundsException: if the index where the collection is to be added is out of bounds
NullPointerException: if the given collection c is null.

The following Java program demonstrates the usage of add and addAll methods.

import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayList city_List=new ArrayList(); //add elements to the ArrayList using add method city_List.add("Delhi"); city_List.add("Mumbai"); city_List.add("Chennai"); city_List.add("Kolkata"); //print the list System.out.println("Initial ArrayList:" + city_List); //add an element at index 1 using add method overload city_List.add(1, "NYC"); //print the list System.out.println("\nrrayList after adding element at index 1:" + city_List); //define a second list ArrayList more_Cities = new ArrayList(Arrays.asList("Pune", "Hyderabad")); //use addAll method to add the list to ArrayList at index 4 city_List.addAll(4,more_Cities); //print the list System.out.println("\nArrayList after adding list at index 4:" + city_List); } }

Output:

Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata]
rrayList after adding element at index 1:[Delhi, NYC, Mumbai, Chennai, Kolkata]
ArrayList after adding list at index 4:[Delhi, NYC, Mumbai, Chennai, Pune, Hyderabad, Kolkata]

The above program uses both the versions of the add method to add elements to the list. It also adds a collection to the list at the specified index. Note the shifting of elements to the right of the ArrayList as evident from the output of the program.

ArrayList Add To The Front

As already mentioned, the first version of the add method adds the elements to the end of the list. If you want to add the elements at the beginning of the ArrayList, then you have to make use of the second version of the add method. This add method takes an index as a parameter. This index is the position at which the element is to be added.

Thus to add the element at the beginning of the list, you have to specify the index as 0 which is the start of the list.

The following program adds an element to the front of the ArrayList.

import java.util.ArrayList; public class Main { public static void main(String[] args) { //define new ArrayList and initialize it ArrayList numList = new ArrayList(); numList.add(5); numList.add(7); numList.add(9); //print the ArrayList System.out.println("Initial ArrayList:"); System.out.println(numList); //use add method with index=0 to add elements to the beginning of the list numList.add(0, 3); numList.add(0, 1); System.out.println("ArrayList after adding elements at the beginning:"); //print ArrayList System.out.println(numList); } }

Output:

Initial ArrayList:
[5, 7, 9]
ArrayList after adding elements at the beginning:
[1, 3, 5, 7, 9]

ArrayList remove

I.

Prototype: E remove (int index)
Parameters: index=> Position at which the element is to be removed from the ArrayList.
Return Value: E=> Element that is deleted
Description: Deletes element at the ‘index’ in the ArrayList and moves subsequent elements to the left.
Exceptions: IndexOutOfBoundsException => Index specified is out of range.

II.

Prototype: boolean remove (Object o)
Parameters: o=> Element that is to be removed from the ArrayList.
Return Value: true=> If the element is present in the list.

Description: Deletes the first occurrence of element o from the list. If the element is not present in the list, then there is no effect of this operation. Once the element is deleted, the subsequent elements are shifted to the left.

ArrayList removeAll

Prototype: boolean removeAll (Collection c)
Parameters: c=> Collection whose elements match with those of ArrayList and are to be removed.
Return Value: true=> If the ArrayList is altered by the operation.

Description: Removes all the elements from the list that match the elements in the given collection c. As a result, the elements remaining are shifted to the left of the list.

Exceptions: ClassCastException => Class is not the same as that of the specified collection which implies class is incompatible.
NullPointerException => If the given collection c is null; or if c has a null element and it is not allowed by the collection.

ArrayList removeRange

Prototype: protected void removeRange (int fromIndex, int toIndex)
Parameters: fromIndex=> Index of the starting element of the range to be removed.
toIndex=> Index of the element after the last element in the range to be removed.
Return Value: void
Description: Removes elements specified in the given range, fromIndex (inclusive) to toIndex (exclusive) from the list. This operation shortens the length of the list by (toIndex-fromIndex). This operation has no effect in case fromIndex = toIndex.
Exceptions: IndexOutOfBoundsException=> If any of the indices (fromIndex or toIndex) is out of bounds.

Let us implement a Java program to demonstrate some of these remove methods that we discussed above.

import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayList city_List=new ArrayList(Arrays.asList("Delhi","Mumbai","Chennai", "Kolkata", "Pune", "Hyderabad")); //print the list System.out.println("Initial ArrayList:" + city_List); //remove element at index 2 city_List.remove(2); //print the list System.out.println("\nArrayList after removing element at index 2:" + city_List); //remove the element "Kolkata" city_List.remove("Kolkata"); //print the list System.out.println("\nArrayList after removing element -> Kolkata:" + city_List); //create new list ArrayList newCities=new ArrayList(Arrays.asList("Delhi","Hyderabad")); //call removeAll to remove elements contained in newCities list. city_List.removeAll(newCities); //print the list System.out.println("\nArrayList after call to removeAll:" + city_List); } }

Output:

Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata, Pune, Hyderabad
ArrayList after removing element at index 2:[Delhi, Mumbai, Kolkata, Pune, Hyderabad]
ArrayList after removing element -> Kolkata:[Delhi, Mumbai, Pune, Hyderabad]
ArrayList after call to removeAll:[Mumbai, Pune]

ArrayList size (Length)

Prototype: int size ()
Parameters: NIL
Return Value: int=> Number of elements in the ArrayList.
Description: Returns the total number of elements or the length of the ArrayList.

EnsureCapacity

Prototype: void ensureCapacity (int minCapacity)
Parameters: minCapacity=> The minimum capacity desired for the ArrayList.
Return Value: void
Description: Increases the capacity of the ArrayList to ensure that it has the minCapacity.

trimToSize

Prototype: void trimToSize()
Parameters: NIL
Return Value: void
Description: Trims the ArrayList capacity to the size or number of elements present in the list.

The below programming example demonstrates the methods size (), ensureCapacity () and trimToSize ().

import java.util.ArrayList; public class Main { public static void main(String [] args) { //Create and initialize Arraylist ArrayList evenList=new ArrayList(5); System.out.println("Initial size: "+evenList.size()); evenList.add(2); evenList.add(4); evenList.add(6); evenList.add(8); evenList.add(10); //print the list and size System.out.println("Original List: " + evenList); System.out.println("ArrayList Size after add operation: "+evenList.size()); //call ensureCapacity () with minimum capacity =10 evenList.ensureCapacity(10); //add two more elements evenList.add(12); evenList.add(14); //print the size again System.out.println("ArrayList Size after ensureCapacity() call and add operation: "+evenList.size()); //call trimToSize() evenList.trimToSize(); //print the size and the ArrayList System.out.println("ArrayList Size after trimToSize() operation: "+evenList.size()); System.out.println("ArrayList final: "); for(int num: evenList){ System.out.print(num + " "); } } }

Output:

Initial size: 0
Original List: [2, 4, 6, 8, 10]
ArrayList Size after add operation: 5
ArrayList Size after ensureCapacity() call and add operation: 7
ArrayList Size after trimToSize() operation: 7
ArrayList final:
2 4 6 8 10 12 14

ArrayList contains

Prototype: boolean contains (Object o)
Parameters: o=> Element which is to be checked if present in the ArrayList.
Return Value: true=> If the ArrayList contains element o.
Description: Checks if the list contains the given element ‘o’. Returns true if the element is present.

We make use of the ‘contains’ method in the following program.

import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayList colorsList = new ArrayList(); colorsList.add("Red"); colorsList.add("Green"); colorsList.add("Blue"); colorsList.add("White"); //call contains method to check if different strings are present in ArrayList System.out.println("ArrayList contains ('Red Green'): " +colorsList.contains("Red Green")); System.out.println("ArrayList contains ('Blue'): " +colorsList.contains("Blue")); System.out.println("ArrayList contains ('Yellow'): " +colorsList.contains("Yellow")); System.out.println("ArrayList contains ('White'): " +colorsList.contains("White")); } }

Output:

ArrayList contains (‘Red Green’): false
ArrayList contains (‘Blue’): true
ArrayList contains (‘Yellow’): false
ArrayList contains (‘White’): true

As shown in the above output, the ‘contains’ method checks if the argument provided is present in the ArrayList and returns true or false.

ArrayList get

Prototype: E get (int index)
Parameters: index=> Index at which element is to be retrieved from the ArrayList.
Return Value: E=> Element value at the given index in the ArrayList.
Description: Returns the element in the list present at the position specified by ‘index’.
Exceptions: IndexOutOfBoundsException => If index is out of bounds.

ArrayList set (Replace element)

Prototype: E set (int index, E element)
Parameters: index=> Index at which the element is to be replaced.
Element=> New element to be set at the index specified.
Return Value: E => Element that is replaced by the set operation.
Description: Sets the element value at the given ‘index’ to the new value given by ‘element’.
Exceptions: IndexOutOfBoundsException => If index is out of bounds

The Java program below uses get () and set () method to retrieve and replace values in the ArrayList.

import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayList colorsList = new ArrayList(); colorsList.add("Red"); colorsList.add("Green"); colorsList.add("Blue"); colorsList.add("White"); //call get () method to retrieve value at index 2 System.out.println("Entry at index 2 before call to set: " + colorsList.get(2)); //replace the value at index 2 with new value colorsList.set(2,"Yellow"); //print the value at index 2 again System.out.println("Entry at index 2 after call to set: " + colorsList.get(2)); } }

Output:

Entry at index 2 before call to set: Blue
Entry at index 2 after call to set: Yellow

ArrayList clear

Prototype: void clear ()
Parameters: NIL
Return Value: void
Description: Clears the list by removing all the elements from the list.

ArrayList isEmpty

Prototype: boolean isEmpty ()
Parameters: NIL
Return Value: true=> if list is empty
Description: Checks if the given list is empty.

Clear () and isEmpty () functions are demonstrated below.

import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayList colorsList = new ArrayList(); colorsList.add("Red"); colorsList.add("Green"); colorsList.add("Blue"); colorsList.add("White"); //print the ArrayList System.out.println("The ArrayList: " + colorsList); //call clear() nethod on ArrayList colorsList.clear(); //check if ArrayList is empty using isEmpty() method System.out.println("Is ArrayList empty after clear ()? :" + colorsList.isEmpty()); } }

Output:

The ArrayList: [Red, Green, Blue, White]
Is ArrayList empty after clear ()? :true

ArrayList indexOf

Prototype: int indexOf (Object o)
Parameters: o=> Element whose index is to be found in the ArrayList.
Return Value: int => Index of the first occurrence of the element in the list.
Description: Returns the index of the first occurrence of the element o in the list. -1 if the element o is not present in the list.

ArrayList lastIndexOf

Prototype: int lastIndexOf (Object o)
Parameters: o=> The element to be searched for.
Return Value: int=> Index of the last occurrence of the element in the list.
Description: Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.

The below Java program demonstrates the indexOf and lastIndexOf methods of ArrayList.

import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize intList ArrayList intList = new ArrayList(); intList.add(1); intList.add(1); intList.add(2); intList.add(3); intList.add(5); intList.add(3); intList.add(2); intList.add(1); intList.add(1); //print the ArrayList System.out.println("The ArrayList: " + intList); //call indexOf() and lastIndexOf() methods to check the indices of specified elements System.out.println("indexOf(1) : " + intList.indexOf(1)); System.out.println("lastIndexOf(1) : " + intList.lastIndexOf(1)); System.out.println("indexOf(2) : " + intList.indexOf(2)); System.out.println("lastIndexOf(2) : " + intList.lastIndexOf(2)); System.out.println("indexOf(3) : " + intList.indexOf(3)); System.out.println("lastIndexOf(3) : " + intList.lastIndexOf(3)); System.out.println("indexOf(5) : " + intList.indexOf(5)); System.out.println("lastIndexOf(5) : " + intList.lastIndexOf(5)); } }

Output:

The ArrayList: [1, 1, 2, 3, 5, 3, 2, 1, 1]
indexOf(1) : 0
lastIndexOf(1) : 8
indexOf(2) : 2
lastIndexOf(2) : 6
indexOf(3) : 3
lastIndexOf(3) : 5
indexOf(5) : 4
lastIndexOf(5) : 4

ArrayList toArray

Prototype: Object [] toArray ()
Parameters: NIL
Return Value: Object [] =>an array. This returned array contains all the elements of the list in a proper sequence.
Description: Converts the given list into an array.

Prototype: T[] toArray (T[] a)

Parameters: a=> Array to store elements of the list. If the size of the array is not enough for list elements, another array with the same type as a is created for storing elements.

Return Value: T[] => Array that contains all the list elements.
Description: Converts the given list into an array of the type given by a.

Exceptions: ArrayStoreException => If there is a mismatch in runtime type of the array and runtime type or supertype of its elements.
NullPointerException => The given array is null

The Java program below demonstrates the toArray method of ArrayList.

import java.util.*; public class Main { public static void main(String[] args) { // define and initialize ArrayList ArrayList intList = new ArrayList(); intList.add(10); intList.add(20); intList.add(30); intList.add(40); intList.add(50); // print ArrayList System.out.println("ArrayList: " + intList); //declare array Integer myArray[] = new Integer[intList.size()]; //use toArray method to convert ArrayList to Array myArray = intList.toArray(myArray); //print the Array System.out.println("Array from ArrayList:" + Arrays.toString(myArray)); } }

Output:

ArrayList: [10, 20, 30, 40, 50]
Array from ArrayList:[10, 20, 30, 40, 50]

ArrayList clone

Prototype: Object clone ()
Parameters: NIL
Return Value: Object=> Clone of the ArrayList instance.
Description: Makes a shallow copy of the given ArrayList.

import java.util.ArrayList; public class Main { public static void main(String a[]){ ArrayList fruitsList = new ArrayList(); //Adding elements to the ArrayList fruitsList.add("Apple"); fruitsList.add("Orange"); fruitsList.add("Melon"); fruitsList.add("Grapes"); System.out.println("Original ArrayList: "+fruitsList); ArrayList clone_list = (ArrayList)fruitsList.clone(); System.out.println("Cloned ArrayList: "+ clone_list); //add one elmeent & remove one element from original arraylist fruitsList.add("Mango"); fruitsList.remove("Orange"); //print original and cloned ArrayList again System.out.println("\nOriginal ArrayList after add & remove:"+fruitsList); System.out.println("Cloned ArrayList after original changed:"+clone_list); } }

Output:

Original ArrayList: [Apple, Orange, Melon, Grapes]
Cloned ArrayList: [Apple, Orange, Melon, Grapes]
Original ArrayList after add & remove:[Apple, Melon, Grapes, Mango]
Cloned ArrayList after original changed:[Apple, Orange, Melon, Grapes]

From the above program output, you can see that the cloned ArrayList is a shallow copy of the original ArrayList. This means that when the original ArrayList is changed, these changes do not reflect in the cloned ArrayList as they do not share the memory locations of each element.

For making a deep copy of Array, the original ArrayList needs to be traversed and each of its elements needs to be copied to the destination ArrayList.

ArrayList subList

Prototype: List subList (int fromIndex, int toIndex)
Parameters: fromIndex=> Starting index of the range (inclusive)
toIndex=> End index of the range (exclusive)
Return Value: List => Sublist of the list in the given range.

Description: Returns a subList between a given range, fromIndex to index for the given list. Note that this sublist or the view of the list in the given range supports all the operations supported by the list. No view is returned if fromIndex = toIndex.

Exceptions: IndexOutOfBoundsException => Thrown when toIndex is out of range.
IllegalArgumentException=> If fromIndex > toIndex i.e. indices are out of order.

Let us see an example of the subList method.

import java.util.ArrayList; import java.util.List; class Main{ public static void main(String a[]){ //create and initialize the ArrayList ArrayList intList = new ArrayList(); intList.add(5); intList.add(10); intList.add(15); intList.add(20); intList.add(25); intList.add(30); intList.add(35); intList.add(40); intList.add(45); intList.add(50); //print the ArrayList System.out.println("Original ArrayList: "+intList); //create a sublist for the given ArrayList ArrayList sub_ArrayList = new ArrayList(intList.subList(2, 6)); //print the sublist System.out.println("Sublist of given ArrayList: "+sub_ArrayList); } }

Output:

Original ArrayList: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Sublist of given ArrayList: [15, 20, 25, 30]

ArrayList retainAll

Prototype: boolean retainAll (Collection c)
Parameters: c=> Collection with elements that are to be retained in the list.
Return Value: true=> If the ArrayList changed as a result of the operation.
Description: Retains those elements in the list that match the elements in the given collection c.

Exceptions: ClassCastException => The collection type and list type do not match
NullPointerException => Given collection is null or the list contains null element and collection does not permit nulls.

The following program demonstrates the retainAll method.

import java.util.*; class Main{ public static void main(String args[]){ //create and initialize ArrayList ArrayList colorsList=new ArrayList(); colorsList.add("Red"); colorsList.add("Green"); colorsList.add("Blue"); colorsList.add("Yellow"); //print the ArrayList System.out.println("Original ArrayList:" + colorsList); //define another collection ArrayList color_collection=new ArrayList(); color_collection.add("Red"); color_collection.add("Blue"); System.out.println("Collection elements to be retained in the list:" + color_collection); //call retainAll method with above collection as an argument colorsList.retainAll(color_collection); //print the ArrayList after retainAll call. System.out.println("ArrayList after retainAll call:" + colorsList); } }

Output:

Original ArrayList:[Red, Green, Blue, Yellow]
Collection elements to be retained in the list:[Red, Blue]
ArrayList after retainAll call:[Red, Blue]

ArrayList Iterator

Prototype: Iterator iterator ()
Parameters: NIL
Return Value: Iterator => iterator over the list elements.
Description: Returns an iterator to traverse over the list elements in the proper sequence.

ArrayList listIterator

I.

Prototype: ListIterator listIterator ()
Parameters: NIL
Return Value: ListIterator => listIterator over the list elements.
Description: Returns list iterator to traverse over the elements of the given list.

II.

Prototype: ListIterator listIterator (int index)
Parameters: index=> Position of the first element in the listIterator.
Return Value: ListIterator => ListIterator for the list from specified index.
Description: Returns the list iterator starting from the specified position ‘index’ to traverse over the elements of the given list.
Exceptions: IndexOutOfBoundsException => Given index is out of range.

Example of iterator () and listIterator () methods.

import java.util.*; class Main{ public static void main(String args[]){ //create ArrayList and initialize it ArrayList cities=new ArrayList(); cities.add("Mumbai"); cities.add("Pune"); cities.add("Hyderabad"); cities.add("Delhi"); //use iterator() method to traverse through the list System.out.println("List contents using Iterator () method:"); Iterator iter=cities.iterator(); while(iter.hasNext()){ System.out.print(iter.next() + " "); } //use listIterator() method to traverse through the list System.out.println("\n\nList contents using listIterator () method:"); ListIterator list_iter=cities.listIterator(); while(list_iter.hasNext()) { System.out.print(list_iter.next() + " "); } } }

Output:

List contents using Iterator () method:
Mumbai Pune Hyderabad Delhi
List contents using listIterator () method:
Mumbai Pune Hyderabad Delhi

Add Array To ArrayList In Java

ArrayList supports the addAll method to add elements of the collection to the ArrayList. In a similar manner, you can also add an Array to the ArrayList. This is done using the ‘Collections.addAll’ method.

Example of adding an Array to the ArrayList.

import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayList city_List=new ArrayList(); //add elements to the ArrayList using add method city_List.add("Delhi"); city_List.add("Mumbai"); city_List.add("Chennai"); city_List.add("Kolkata"); //print ArrayList System.out.println("\nInitial ArrayList :" + city_List); //define an array. String[] myArray = new String[]{"Cochin", "Goa"}; //add the array to the ArrayList Collections.addAll(city_List,myArray); //print the ArrayList System.out.println("\nArrayList after adding array :" + city_List); } }

Output:

Initial ArrayList :[Delhi, Mumbai, Chennai, Kolkata]
ArrayList after adding array :[Delhi, Mumbai, Chennai, Kolkata, Cochin, Goa]

Sort ArrayList In Java

ArrayList uses the Collections.sort method to sort its elements. By default, the list is sorted in ascending order by the Collections.sort method. If the ArrayList is to be sorted in descending order, then you have to provide ‘Collections.reverseOrder()’ a parameter to the sort method.

Given below is a program to sort an ArrayList in ascending and descending order:

import java.util.*; public class Main { public static void main(String args[]){ //Create and initialize an ArrayList ArrayList colorsList = new ArrayList(); colorsList.add("Red"); colorsList.add("Green"); colorsList.add("Blue"); colorsList.add("Yellow"); //print initial ArrayList System.out.println("Initial ArrayList:" + colorsList); //sort ArrayList in ascending order Collections.sort(colorsList); //print sorted ArrayList System.out.println("\nArrayList sorted in ascending order:"); System.out.println(colorsList); //sort ArrayList in reverse(desending) order Collections.sort(colorsList, Collections.reverseOrder()); //print sorted list System.out.println("\nArrayList sorted in descending order:"); System.out.println(colorsList); } }

Output:

Initial ArrayList:[Red, Green, Blue, Yellow]
ArrayList sorted in ascending order:
[Blue, Green, Red, Yellow]
ArrayList sorted in descending order:
[Yellow, Red, Green, Blue]

In case the ArrayList contains other class objects as elements, then you can make use of Comparable and Comparator interfaces. More details about interfaces will be covered in our later tutorials.

Reverse An ArrayList In Java

You can also reverse an ArrayList in Java. One method to do this is to use the traditional method of traversing the ArrayList in the reverse order and copy each element to a new ArrayList.

Another method is using the Collections class which provides the ‘reverse’ method that is used to reverse a collection.

The program to reverse an ArrayList using the Collections class is given below.

import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { // create and initialize an ArrayList ArrayList oddList = new ArrayList(); oddList.add(1); oddList.add(3); oddList.add(5); oddList.add(7); oddList.add(9); System.out.print("Initial ArrayList: " + oddList); // use Collections.reverse method to reverse the ArrayList Collections.reverse(oddList); //print the ArrayList System.out.print("\nReversed ArrayList: " + oddList); } }

Output:

Initial ArrayList: [1, 3, 5, 7, 9]
Reversed ArrayList: [9, 7, 5, 3, 1]

Remove Duplicates From An ArrayList In Java

To remove duplicates from the ArrayList, you can once again resort to the traditional method of using an iterator to traverse through the ArrayList and store only the first occurrence of the element into a different ArrayList.

Yet another method is by using the ‘distinct ()’ method of stream () class. This method returns a stream of distinct elements. The stream () feature is available in Java from Java 8 onwards.

The implementation of stream ().distinct () method is given below:

import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Create an ArrayList of numbers ArrayList numList = new ArrayList<> (Arrays.asList(1, 2, 3, 1, 3, 5, 5, 6, 6, 7, 7, 8, 8)); //print the original ArrayList System.out.println("Original ArrayList:" + numList); //Use Java 8 stream().distinct() method to remove duplicates from the list List distinctList = numList.stream().distinct().collect(Collectors.toList()); //print the new list System.out.println("ArrayList without duplicates:" + distinctList); } }

Output:

Original ArrayList:[1, 2, 3, 1, 3, 5, 5, 6, 6, 7, 7, 8, 8]
ArrayList without duplicates:[1, 2, 3, 5, 6, 7, 8]

Shuffle (Randomize) An ArrayList In Java

You can also ‘shuffle’ or randomize the ArrayList elements. This is done using the Collections.shuffle () method. Using this method, either you can shuffle the ArrayList with default settings or provide a random () function that will randomize the elements according to the random value provided.

A Java program to achieve this is given below.

import java.util.*; public class Main { public static void main(String[] args) { //create and initialize a String ArrayList ArrayList strlist = new ArrayList(); strlist.add("east"); strlist.add("west"); strlist.add("north"); strlist.add("south"); strlist.add("southwest"); strlist.add("northeast"); //print the original list System.out.println("Original ArrayList : \n" + strlist); //shuffle the ArrayList without random function Collections.shuffle(strlist); System.out.println("\nShuffled ArrayList without Random() : \n" + strlist); // shuffle the ArrayList with random() function Collections.shuffle(strlist, new Random()); System.out.println("\nShuffled ArrayList with Random() : \n" + strlist); // use random (2) to shuffle the ArrayList Collections.shuffle(strlist, new Random(2)); System.out.println("\nShuffled ArrayList with Random(2) : \n" + strlist); } }

Output:

Original ArrayList :[east, west, north, south, southwest, northeast] Shuffled ArrayList without Random() :[north, northeast, east, southwest, south, west]
Shuffled ArrayList with Random() :[south, east, north, northeast, west, southwest]
Shuffled ArrayList with Random(2) :[southwest, south, east, northeast, north, west]

Frequently Asked Questions

Q #1) What is the difference between Homogeneous and Heterogeneous containers in Java?

Answer: Homogeneous containers contain objects/elements of the same type. On the other hand, heterogeneous containers have objects of mixed type.

Q #2) Is ArrayList in Java Heterogeneous?

Answer: Yes. Since ArrayLists support generics and therefore type erasure, it can contain mixed objects when implemented as a generic ArrayList.

Q #3) Can ArrayList store int?

Answer: No. ArrayLists cannot store values like int but it can store Integer objects as ArrayLists can contain only objects. Thus to store primitive types you should use wrapper classes like Integer for ints.

Q #4) What happens when ArrayList is full?

Answer: Every ArrayList object has a feature named ‘capacity’. When the ArrayList is full, the capacity of the ArrayList increases automatically to make room for more elements.

Q #5) What is the difference between the removeAll and retainAll method in ArrayList?

Answer: The ArrayList methods ‘removeAll’ and ‘retainAll’ exhibit opposite behavior.

While the removeAll method removes all the elements from the list that match with the collection passed as an argument to this method, retainAll, on the other hand, retains all the elements in the list that match with that of the collection.