In this Tutorial, we will Discuss Java ArrayList Methods such as add, addAll, remove, removeAll, size, contains, retainAll, Sort, Reverse, etc. with Examples:
In the previous tutorial, we explored the ArrayList data structure, and the ArrayList class provided for this data structure/collection in Java. We have learned creation, initialization, etc. of the ArrayList objects.
Apart from these features that help us to define ArrayList, the ArrayList class in Java also provides a full-fledged function API that consists of methods that are used to manipulate ArrayList objects.
=> Check ALL Java Tutorials Here.
These methods allow us to add, delete, search elements in the ArrayList as well as to retrieve the length/size of ArrayList elements, etc.
In this tutorial, we will discuss these methods in detail with simple programming examples.
Table of Contents:
- ArrayList Methods In Java
- ArrayList add
- ArrayList addAll
- ArrayList Add To The Front
- ArrayList remove
- ArrayList removeAll
- ArrayList removeRange
- ArrayList size (Length)
- ArrayList contains
- ArrayList get
- ArrayList set (Replace element)
- ArrayList clear
- ArrayList isEmpty
- ArrayList indexOf
- ArrayList lastIndexOf
- ArrayList toArray
- ArrayList clone
- ArrayList subList
- ArrayList retainAll
- ArrayList Iterator
- ArrayList listIterator
- Add Array To ArrayList In Java
- Sort ArrayList In Java
- Reverse An ArrayList In Java
- Remove Duplicates From An ArrayList In Java
- Shuffle (Randomize) An ArrayList In Java
- Frequently Asked Questions
- Conclusion
ArrayList Methods In Java
The following table lists all the methods that are provided by the ArrayList class.
Method | Method Prototype | Method Description |
---|---|---|
Add | boolean 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’. | |
AddAll | boolean addAll (Collection c) | Adds all the elements in the given collection c to the end of the list. |
boolean addAll (int index, Collection c) | Adds all the elements in the given collection c at the position specified by the ‘index’ in the list. | |
Clear | void clear() | Clears the list by removing all the elements from the list. |
Clone | Object clone() | Makes a shallow copy of the given ArrayList. |
Contains | boolean contains(Object o) | Checks if the list contains the given element ‘o’. Returns true if the element is present. |
ensureCapacity | void ensureCapacity (int minCapacity) | Increases the capacity of the ArrayList to ensure it has the minCapacity. |
Get | E get(int index) | Returns the element in the list present at the position specified by ‘index’. |
indexOf | int 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. |
isEmpty | boolean isEmpty() | Checks if the given list is empty. |
Iterator | Iterator | Returns an iterator to traverse over the list elements in the proper sequence. |
lastIndexOf | int 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. |
listIterator | ListIterator< E > listIterator() | Returns list iterator to traverse over the elements of the given list. |
ListIterator< E > listIterator(int index) | Returns the list iterator starting from the specified position ‘index’ to traverse over the elements of the given list. | |
remove | E 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. | |
removeAll | boolean removeAll(Collection< ? > c) | Removes all the elements from the list that match the elements in given collection c. |
removeRange | protected void removeRange (int fromIndex, int toIndex) | Removes elements specified in the given range, fromIndex (inclusive) to toIndex (exclusive) from the list. |
retainAll | boolean retainAll(Collection< ? > c) | Retains those elements in the list that match the elements in the given collection c. |
set | E set(int index, E element) | Sets the element value at given ‘index’ to the new value given by ‘element’. |
size | int size() | Returns the total number of elements or length of the list. |
subList | List< E > subList(int fromIndex, int toIndex) | Returns a subList between given range, fromIndex to toIndex for the given list. |
toArray | Object[] toArray() | Converts the given list into an array. |
< T > T[] toArray(T[] a) | Converts the given list into an array of the type given by a. | |
trimToSize | void 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<? extends E> 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<? extends E> 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<String> city_List=new ArrayList<String>(); //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<String> more_Cities = new ArrayList<String>(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<Integer> numList = new ArrayList<Integer>(); 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<String> city_List=new ArrayList<String>(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<String> newCities=new ArrayList<String>(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<Integer> evenList=new ArrayList<Integer>(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<String> colorsList = new ArrayList<String>(); 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<String> colorsList = new ArrayList<String>(); 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<String> colorsList = new ArrayList<String>(); 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<Integer> intList = new ArrayList<Integer>(); 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> 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<Integer> intList = new ArrayList<Integer>(); 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<String> fruitsList = new ArrayList<String>(); //Adding elements to the ArrayList fruitsList.add("Apple"); fruitsList.add("Orange"); fruitsList.add("Melon"); fruitsList.add("Grapes"); System.out.println("Original ArrayList: "+fruitsList); ArrayList<String> clone_list = (ArrayList<String>)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<E> subList (int fromIndex, int toIndex)
Parameters: fromIndex=> Starting index of the range (inclusive)
toIndex=> End index of the range (exclusive)
Return Value: List<E> => 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<Integer> intList = new ArrayList<Integer>(); 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<Integer> sub_ArrayList = new ArrayList<Integer>(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<String> colorsList=new ArrayList<String>(); 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<String> color_collection=new ArrayList<String>(); 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<E> iterator ()
Parameters: NIL
Return Value: Iterator <E> => iterator over the list elements.
Description: Returns an iterator to traverse over the list elements in the proper sequence.
ArrayList listIterator
I.
Prototype: ListIterator<E> listIterator ()
Parameters: NIL
Return Value: ListIterator <E> => listIterator over the list elements.
Description: Returns list iterator to traverse over the elements of the given list.
II.
Prototype: ListIterator<E> listIterator (int index)
Parameters: index=> Position of the first element in the listIterator.
Return Value: ListIterator<E> => 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<String> cities=new ArrayList<String>(); 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<String> 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<String> city_List=new ArrayList<String>(); //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<String> colorsList = new ArrayList<String>(); 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<Integer> oddList = new ArrayList<Integer>(); 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<Integer> 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<Integer> 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<String> strlist = new ArrayList<String>(); 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.
Conclusion
In this tutorial, we have discussed ArrayList methods in detail with an example.
We have also considered some special cases like adding elements to the front of the list. We also discussed other operations on ArrayList like sorting, reversing, and shuffling of ArrayList.
In our upcoming tutorial, we will discuss some of the ArrayList conversions.
=> Watch Out The Simple Java Training Series Here.