Java Arraylist tutorial with examples will help you understand how to use ArrayList in Java in an easy way. ArrayList in Java is an implementation of the List interface which grows automatically as we add elements to it.
Difference between array and ArrayList: Java arrays are fixed in size, which means the size of an array cannot be changed once it is created, while the ArrayList in Java can grow and shrink in size as we add or remove elements from it. Java ArrayList uses an array internally to store its elements.
The ArrayList class implements all the optional operations defined by the List interface. It also allows null elements. Like an array, elements of an ArrayList can be accessed using an index. ArrayList index starts from 0 to ArrayList.size() – 1
. The ArrayList class is a part of the Java Collection Framework.
Since the ArrayList class also implements the RandomAccess interface, its elements can be accessed randomly by specifying the index. This operation is a constant time operation.
The length of an internal array maintained by the ArrayList is called the capacity of the ArrayList. As you add elements to the ArrayList, the ArrayList capacity grows automatically.
How to create an ArrayList object?
The ArrayList class in Java provides several constructors using which we can create new objects of the ArrayList class. The default constructor of the ArrayList class creates a new empty ArrayList object. The below given statement will create an empty ArrayList of String type.
1 |
ArrayList<String> listStrings = new ArrayList<String>(); |
There is an overloaded ArrayList constructor that accepts the Collection type as a parameter.
1 |
public ArrayList(Collection <? extends E> collection) |
This constructor creates an ArrayList object containing all the elements of the specified collection. Below given example shows how to copy an ArrayList to another ArrayList using this constructor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * To copy an ArrayList to another ArrayList, use the * constructor having the Collection parameter */ ArrayList<Integer> aListCopy = new ArrayList<Integer>( aListNumbers ); System.out.println("Copy ArrayList to another ArrayList: "); System.out.println("Original ArrayList: " + aListNumbers); System.out.println("Copied ArrayList: " + aListCopy); |
Output
1 2 3 |
Copy ArrayList to another ArrayList: Original ArrayList: [1, 2, 3] Copied ArrayList: [1, 2, 3] |
How to add elements to ArrayList using the add method?
The add
method of the ArrayList class adds the specified element at the end of the ArrayList object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); /* * To add elements to the ArrayList, use the * add method. * * It appends the given element at the end of the ArrayList */ aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); System.out.println("ArrayList contains: " + aListNumbers); |
Output
1 |
ArrayList contains: [1, 2, 3] |
Please note that primitive type like int or double cannot be added to the ArrayList, only objects can be. if you want to store primitive types, you can first convert it to the respective wrapper objects like Integer or Double and then add them to the ArrayList.
How to insert an element in the ArrayList at the specified index using the add method?
The above given add
method appends an element at the end of the ArrayList. What if you want to insert an element in between or at the specified index? Well, there is an overloaded add
method that accepts the element to insert as well as the index to which we want to insert an element.
1 |
public void add(int index, E element) |
This method inserts an element at the given index in the ArrayList and shifts subsequent elements to the right (i.e. 1 is added to their existing index).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * To insert an element to the ArrayList, use the * add method with an index parameter */ //this will insert an element at index 2 aListNumbers.add(2, 22); System.out.println("ArrayList contains: " + aListNumbers); |
Output
1 |
ArrayList contains: [1, 2, 22, 3] |
As you can see from the output, the element 22 is inserted at index 2. The element 3 was previously at index 2, but now it is shifted to the right by adding 1 to its index.
How to add an element at the front of the ArrayList?
The default add
method appends an element at the end of the ArrayList. If you want to add an element at the front of the ArrayList or the start of the ArryList, use the add
method with the element and index parameters and specify the index as 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * To add element at the front of the ArrayList, use the * add method and specify the element you want to add * and index as 0. */ //this will insert 999 at the beginning of the ArrayList aListNumbers.add(0, 999); System.out.println("ArrayList elements: " + aListNumbers); |
Output
1 |
ArrayList elements: [999, 1, 2, 3] |
How to replace an element in the ArrayList using the set method?
The set
method of the ArrayList class replaces an element with the specified new element located at the given index. It returns the old element which was replaced by the new element at the specified index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * To replace an element in the ArrayList, use the * set method and specify the index and new element. */ System.out.println( "ArrayList replce element: "); //this will replace 2 with 22 and will return 2 i.e. old element System.out.println( aListNumbers.set(1, 22) ); System.out.println("ArrayList elements: " + aListNumbers); |
Output
1 2 3 |
ArrayList replce element: 2 ArrayList elements: [1, 22, 3] |
Note: Always make sure to check the size first to avoid the IndexOutOfBoundsException while replacing an element in the ArrayList.
How to get the size of an ArrayList using the size method (ArrayList length)?
The size
method of the ArrayList class returns the number of elements that are stored in the ArrayList object. It returns 0 if the ArrayList is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); /* * To get the size of ArrayList, use the * size method. */ //this will print 0 as the ArrayList is empty System.out.println( "ArrayList size: " + aListNumbers.size() ); //add an element aListNumbers.add(50); //this will print 1 as the ArrayList has 1 element System.out.println( "ArrayList size: " + aListNumbers.size() ); |
Output
1 2 |
ArrayList size: 0 ArrayList size: 1 |
How to get elements from an ArrayList using the get method?
The get
method of the ArrayList in Java returns an element stored at the specified index. ArrayList index starts at 0 and ends at ArrayList’s size – 1 index.
1 2 3 4 5 6 7 8 9 10 11 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * To get the elements from an ArrayList, use the * get method and specify the index. */ //this will print 1 System.out.println( "ArrayList element at 0 index: " + aListNumbers.get(0) ); |
Output
1 |
ArrayList element at 0 index: 1 |
Note: Always make sure to check the size of the ArrayList object before getting the element using the index. The get method throws IndexOutOfBoundsException exception if the specified index is out of the range i.e. if the index is less than 0 or index is greater than or equal to the ArrayList size.
How to get the first element of an ArrayList?
Since the ArrayList index starts at 0, the first element of an ArrayList is located at index 0, not 1. Use the get
method and specify the index 0 to get the first element of the ArrayList.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * always make sure to check the size first to * avoid IndexOutOfBoundsException */ if( aListNumbers.size() > 0 ){ /* * To get the first element of an ArrayList, use * the get method and specify the index as 0 */ System.out.println( "ArrayList first element: " + aListNumbers.get(0) ); } |
Output
1 |
ArrayList first element: 1 |
How to get the last element of an ArrayList?
The ArrayList index ends at the size – 1 index. So, the last element of the ArrayList is located at that index.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); /* * always make sure to check the size first to * avoid IndexOutOfBoundsException */ if( aListNumbers.size() > 0 ){ /* * To get the last element of an ArrayList, use * the get method and specify the index as size - 1 */ System.out.println( "ArrayList last element: " + aListNumbers.get( aListNumbers.size() - 1 ) ); } |
Output
1 |
ArrayList last element: 3 |
How to check if ArrayList is empty using the isEmpty method?
The isEmpty
method of the ArrayList class returns true if the ArrayList contains no elements. If the ArrayList contains at least one element, it returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); /* * To check if the ArrayList is empty, use the * isEmpty method. */ //this will print true, as the ArrayList is empty System.out.println( "Is ArrayList empty?: " + aListNumbers.isEmpty() ); //add an element aListNumbers.add(101); //this will print false, as the ArrayList contains one element System.out.println( "Is ArrayList empty?: " + aListNumbers.isEmpty() ); |
Output
1 2 |
Is ArrayList empty?: true Is ArrayList empty?: false |
You can also compare the ArrayList size with 0 to check if the ArrayList is empty. However, the isEmpty
method is recommended way to check as it clearly states the purpose of the code and it more readable.
How to check if ArrayList contains the specified element using the contains method?
The contains
method returns true if the ArrayList contains the specified element. It returns false if the list does not contain the specified element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); /* * To check if the ArrayList contains the specified element, use * the contains method */ //this will return true as the ArrayList contains element "Green" System.out.println( "ArrayList contains Red: " + aListBasicColors.contains("Red") ); //this will return false as the ArrayList does not contain element "Yellow" System.out.println( "ArrayList contains Yellow: " + aListBasicColors.contains("Yellow") ); |
Output
1 2 |
ArrayList contains Red: true ArrayList contains Yellow: false |
The contains
method returns a boolean indicating whether the ArrayList contains an element or not. If you want to get the index of the element in the ArrayList, use the below given indexOf
and lastIndexOf
methods.
How to search elements in the ArrayList using the indexOf and lastIndexOf methods?
How to search the first occurrence of the element using the indexOf method?
The indexOf
method returns the index of the first occurrence of the specified element in the ArrayList. If the list does not contain the specified element, it returns -1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
ArrayList<String> aListColors = new ArrayList<String>(); aListColors.add("Red"); aListColors.add("Green"); aListColors.add("Blue"); aListColors.add("Red"); aListColors.add("Yellow"); aListColors.add("Blue"); aListColors.add("White"); /* * To get an index of the first occurrence of the element, use the * indexOf method. */ //this will return 0 i.e. the index where the first "Red" is located in the list System.out.println( aListColors.indexOf("Red") ); //this will return -1, as the list does not contain "Black" System.out.println( aListColors.indexOf("Black") ); |
Output
1 2 |
0 -1 |
How to search the last occurrence of the element using the lastIndexOf method?
The lastIndexOf
method returns the index of the last occurrence of the specified element in the ArrayList. It returns -1 if the element is not found in the ArrayList.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
ArrayList<String> aListColors = new ArrayList<String>(); aListColors.add("Red"); aListColors.add("Green"); aListColors.add("Blue"); aListColors.add("Red"); aListColors.add("Yellow"); aListColors.add("Blue"); aListColors.add("White"); /* * To search the last index of the specified element, use * the lastIndexOf method. */ //this will return 3, i.e. the index where the last "Red" is located in the list System.out.println( aListColors.lastIndexOf("Red") ); //this will return 1, i.e. the only index where "Green" is located System.out.println( aListColors.lastIndexOf("Green") ); //this will return -1 because list does not contain the "Black" System.out.println( aListColors.lastIndexOf("Black") ); |
Output
1 2 3 |
3 1 -1 |
How to Iterate ArrayList in Java?
There are several ways using which you can iterate ArrayList in Java.
1. Iterate ArrayList using a while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using while loop */ int index = 0; while( index < aListNumbers.size() ){ System.out.println( aListNumbers.get(index) ); //increment index by 1 index++; } |
2. Iterate ArrayList using a for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using for loop */ for(int index = 0; index < aListNumbers.size(); index++){ System.out.println( aListNumbers.get(index) ); } |
3. Iterate ArrayList using an enhanced for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using enhanced for loop */ for(Integer i : aListNumbers){ System.out.println( i ); } |
4. Iterate ArrayList using Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using Iterator */ //get an Iterator over ArrayList elements Iterator<Integer> iterator = aListNumbers.iterator(); //iterate using hasNext and next methods while( iterator.hasNext() ){ System.out.println( iterator.next() ); } |
5. Iterate ArrayList using ListIterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using ListIterator */ //get a ListIterator over ArrayList elements ListIterator<Integer> listIterator = aListNumbers.listIterator(); //iterate using hasNext and next methods while( listIterator.hasNext() ){ System.out.println( listIterator.next() ); } |
The below given example shows how to iterate an ArrayList in reverse direction of backward direction using the ListIterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * Iterate elements of an ArrayList using ListIterator * in backward direction */ //get a ListIterator over ArrayList elements and specify ArrayList size ListIterator<Integer> listIterator = aListNumbers.listIterator(aListNumbers.size()); //iterate in reverse direction using hasPrevious and previous methods while( listIterator.hasPrevious() ){ System.out.println( listIterator.previous() ); } |
Output
1 2 3 4 5 |
5 4 3 2 1 |
Please visit how to iterate ArrayList in Java example to know more.
How to remove elements from the ArrayList?
1. How to remove an element from the ArrayList using the remove method?
The remove
method removes an element at the specified index of the ArrayList object. All the subsequent elements are shifted to the left by reducing their indices by 1. The remove
method returns an element that was removed from the list.
1 |
public E remove(int index) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); /* * To remove an element from the ArrayList, use the * remove method and specify the index from where you * want to remove an element. */ //this will remove "Green", i.e. element at index 1 System.out.println( aListBasicColors.remove(1) ); System.out.println("ArrayList elements: " + aListBasicColors); |
Output
1 2 |
Green ArrayList elements: [Red, Blue] |
There is an overloaded remove method that takes an Object as an argument instead of the index.
1 |
public boolean remove(Object object) |
If the list contains the specified element, the remove
method removes the first occurrence of the specified object from the ArrayList and returns true. If the list does not contain the specified element, the list remains unchanged and this method returns false.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
ArrayList<String> aListColors = new ArrayList<String>(); aListColors.add("Red"); aListColors.add("Green"); aListColors.add("Blue"); aListColors.add("Red"); aListColors.add("Yellow"); aListColors.add("Blue"); aListColors.add("White"); /* * To remove first occurrence of an element from the ArrayList, * use the remove method with the Object parameter. */ //this will remove "Red" from index 0, and will return true System.out.println( aListColors.remove("Red") ); //this will do nothing and returns false, as the list does not contain "Black" System.out.println( aListColors.remove("Black") ); System.out.println("ArrayList elements: " + aListColors); |
Output
1 2 3 |
true false ArrayList elements: [Green, Blue, Red, Yellow, Blue, White] |
Please note that only the first occurrence of the specified object is removed from the ArrayList.
2. How to remove an element from the ArrayList using the iterator?
The remove
method of an Iterator removes an element from the underlying ArrayList while iterating over ArrayList elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); //get an iterator Iterator<String> iterator = aListBasicColors.iterator(); String strColor = null; //iterate ArrayList elements while(iterator.hasNext()){ strColor = iterator.next(); if(strColor.equals("Green")){ /* * Remove the current element using the remove method * of an Iterator class */ iterator.remove(); } } System.out.println("ArrayList elements: " + aListBasicColors); |
Output
1 |
ArrayList elements: [Red, Blue] |
3. How to remove an element from the ArrayList using the ListIterator?
Just like the Iterator, you can use the remove
method of the ListIterator class to remove the current element from the ArrayList while iterating over its elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); //get a ListIterator ListIterator<String> listIterator = aListBasicColors.listIterator(); String strColor = null; //iterate ArrayList elements while(listIterator.hasNext()){ strColor = listIterator.next(); if(strColor.equals("Blue")){ /* * Remove the current element using the remove method * of the ListIterator class */ listIterator.remove(); } } System.out.println("ArrayList elements: " + aListBasicColors); |
Output
1 |
ArrayList elements: [Red, Green] |
4. How to remove all elements from the ArrayList using the clear method?
The clear
method removes all elements from the ArrayList object. The ArrayList becomes empty after this method call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); System.out.println("ArrayList size: " + aListBasicColors.size()); /* * To remove all the elements from an ArrayList, or empty the ArrayList * use the clear method. */ //empty the ArrayList aListBasicColors.clear(); System.out.println("ArrayList empty: " + aListBasicColors.isEmpty()); |
Output
1 2 |
ArrayList size: 3 ArrayList empty: true |
5. How to remove all elements within the given range using the removeRange method?
The removeRange
method removes all the elements from the ArrayList object whose index is between the specified start index and end index. The start index is inclusive while the end index is exclusive.
1 |
protected void removeRange(int startIndex, int endIndex) |
The problem is, the removeRange
method is declared as protected, so only classes in the same package or the subclasses of an ArrayList class can access this method. If you want to use this method, you need to create your own implementation by extending the ArrayList class as given in the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class MyArrayList<E> extends ArrayList<E>{ /* * Override the removeRange method with public modifier */ public void removeRange(int startIndex, int endIndex){ //call ArrayList's removeRange method super.removeRange(startIndex, endIndex); } } public class Example { public static void main(String[] args) { /* * Create instance of MyArrayList instead of an ArrayList */ MyArrayList<String> aListColors = new MyArrayList<String>(); aListColors.add("Red"); aListColors.add("Green"); aListColors.add("Blue"); aListColors.add("Yellow"); aListColors.add("Purple"); aListColors.add("White"); /* * To remove range of elements, use the * removeRange method overridden in the MyArrayList class */ //this will remove elements having index 2, 3, 4 aListColors.removeRange(2, 5); System.out.println("ArrayList elements: " + aListColors); } } |
Output
1 |
ArrayList elements: [Red, Green, White] |
6. How to remove all elements of an ArrayList which are present in another ArrayList?
The removeAll
method removes all the elements from the ArrayList which are also present in the specified Collection object. The removeAll
method returns true if the ArrayList is changed as a result of the method call.
1 |
public boolean removeAll(Collection<?> collection) |
The below given example shows how to remove all elements from one ArrayList which are also present in another ArrayList object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); //another ArrayList ArrayList<Integer> aListOddNumbers = new ArrayList<Integer>(); aListOddNumbers.add(1); aListOddNumbers.add(3); aListOddNumbers.add(5); /* * To remove all elements from one ArrayList which are also present in another ArrayList, * use the removeAll method. */ //this will remove all odd numbers from the aListNumbers aListNumbers.removeAll(aListOddNumbers); System.out.println("ArrayList elements: " + aListNumbers); |
Output
1 |
ArrayList elements: [2, 4] |
Since the removeAll
method accepts the Collection type, you can use any class that implements the Collection interface instead of an ArrayList.
How to clone the ArrayList using the clone method?
The clone
method of the ArrayList returns a shallow copy of this ArrayList object. A shallow copy means only the element references are copied, not the element objects themselves.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
class Student{ private int id; private String name; public Student(int id, String name){ this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //for printing purpose public String toString(){ return "(" + getId() + " => " + getName() + ")"; } } public class Example { public static void main(String[] args) { ArrayList<Student> aListStudents = new ArrayList<Student>(); aListStudents.add( new Student(1, "Raj") ); aListStudents.add( new Student(2, "Jack") ); aListStudents.add( new Student(3, "Ryan") ); aListStudents.add( new Student(4, "Adam") ); aListStudents.add( new Student(5, "Jessica") ); /* * To clone an ArrayList, use the clone method. */ ArrayList<Student> aListClonedList = (ArrayList<Student>) aListStudents.clone(); System.out.println("Original ArrayList elements: " + aListStudents); System.out.println("Cloned ArrayList elements: " + aListClonedList); /* * Adding or removing elements from the original * or cloned ArrayList does not affect the other */ //remove an element from the original ArrayList aListStudents.remove(0); System.out.println(""); System.out.println("After removing an element from the original list"); System.out.println("Original ArrayList elements: " + aListStudents); System.out.println("Cloned ArrayList elements: " + aListClonedList); //add an element to the cloned ArrayList aListClonedList.add( new Student(6, "Jay") ); System.out.println(""); System.out.println("After adding an element to the cloned ArrayList"); System.out.println("Original ArrayList elements: " + aListStudents); System.out.println("Cloned ArrayList elements: " + aListClonedList); /* * However, remember that the clone method creates a shallow copy. * Meaning it only copies the references to the actual element objects. * So changing any element in the original or cloned ArrayList will * change the other list as well. */ //change the actual object in the cloned ArrayList Student tempStudent = aListClonedList.get(1); tempStudent.setId(9999); System.out.println(""); System.out.println("After changing actual object in the cloned ArrayList"); System.out.println("Original ArrayList elements: " + aListStudents); System.out.println("Cloned ArrayList elements: " + aListClonedList); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Original ArrayList elements: [(1 => Raj), (2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] Cloned ArrayList elements: [(1 => Raj), (2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] After removing an element from the original list Original ArrayList elements: [(2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] Cloned ArrayList elements: [(1 => Raj), (2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] After adding an element to the cloned ArrayList Original ArrayList elements: [(2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] Cloned ArrayList elements: [(1 => Raj), (2 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica), (6 => Jay)] After changing actual object in the cloned ArrayList Original ArrayList elements: [(9999 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica)] Cloned ArrayList elements: [(1 => Raj), (9999 => Jack), (3 => Ryan), (4 => Adam), (5 => Jessica), (6 => Jay)] |
Please visit How to deep clone an ArrayList example to know more about deep cloning the ArrayList in Java.
How to convert ArrayList to an array using the toArray method?
The toArray
method of the ArrayList class returns an array containing all elements of this ArrayList (converts ArrayList to array).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ArrayList<String> aListBasicColors = new ArrayList<String>(); aListBasicColors.add("Red"); aListBasicColors.add("Green"); aListBasicColors.add("Blue"); /* * To convert an ArrayList to an array, use the * toArray method. */ //create an empty array with the same type and size String[] strBasicColors = new String[ aListBasicColors.size() ]; //convert ArrayList to String array strBasicColors = aListBasicColors.toArray( strBasicColors ); System.out.println("String array contains: " + Arrays.toString( strBasicColors )); |
Output
1 |
String array contains: [Red, Green, Blue] |
If the specified array is large enough to hold all the elements of an array, the toArray
method returns the same array filled with the elements of the ArrayList. If the specified array is bigger than the ArrayList, the array element that immediately comes after the ArrayList elements is set to null. If the specified array is smaller than the ArrayList size, a new array is allocated, filled with the ArrayList elements and returned.
Even though you can pass an array of any length to the toArray
method, it is always recommended to pass the array of the same size to the toArray
method to avoid the performance penalty of the creation of a new array.
What is ArrayList capacity?
The ArrayList class internally maintains an array to store its elements. The size of this internal array or buffer is known as the ArrayList capacity. ArrayList grows automatically as and when we add more elements to it by allocating a new bigger size array.
Why do we need to bother about the ArrayList capacity if it is automatically managed by the ArrayList class? Well, the allocation of a new array is a costly operation in terms of performance. Imagine you have an ArrayList having 1,00,000 elements and you want to add 50,000 more elements to it. In that case, the ArrayList class has to allocate new memory for an array big enough to hold the 1,50,000 elements and copy all existing 1,00,000 elements to the new bigger array. This is a very very costly operation.
We can avoid this if we know the approximate number of elements ArrayList is going to hold beforehand. We can then create an ArrayList object with the required capacity to avoid the reallocation when we add elements to it. The below given constructor creates an ArrayList with the specified capacity.
1 |
public ArrayList(int initialCapacity) |
If you want to add a very large number of elements to an existing ArrayList object, you can use the ensureCapacity
method first to make sure that the ArrayList can hold at least the specified number of elements before reallocation of an internal buffer is needed.
Please visit the ArrayList capacity tutorial to know more about how to efficiently manage the capacity of ArrayList.
How to get the sublist from the ArrayList using the subList method?
The subList
method returns a portion of the ArrayList containing elements whose index is between the given start and end index.
1 |
public List<E> subList(int startIndex, int endIndex) |
The startIndex is inclusive while the endIndex is exclusive, means the element at the given startIndex will be included in the sublist but the element at the endIndex will not be.
The sublist returned from this method is backed by the original ArrayList object, so if you make any changes to the sublist, it will be reflected in the ArrayList, and vice versa.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); /* * To get a sublist from ArrayList, use the * subList method. */ //this will returns a sublist containing "2", "3" and "4" List<Integer> sublist = aListNumbers.subList(1, 4); System.out.println("sublist elements: " + sublist); /* * Changing the sublist will change the ArrayList * too, and vice versa */ //replace first element of sublist i.e. "2" with "222" sublist.set(0, 222); System.out.println("sublist elements: " + sublist); System.out.println("arraylist elements: " + aListNumbers); |
Output
1 2 3 |
sublist elements: [2, 3, 4] sublist elements: [222, 3, 4] arraylist elements: [1, 222, 3, 4, 5] |
How to sort an ArrayList in Java?
The sort
method of the ArrayList class sorts the ArrayList elements according to the specified Comparator.
1 |
public void sort(Comparator<? super E> comparator) |
The below given example shows how to sort an ArrayList of Integer in descending order using a Comparator and the sort
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class DescendingComparator implements Comparator<Integer>{ /* * This comparator sorts Integer objects * in descending order */ public int compare(Integer i1, Integer i2) { return i2 - i1; } } public class Example { public static void main(String[] args) { ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(3); aListNumbers.add(2); aListNumbers.add(5); aListNumbers.add(4); System.out.println("ArrayList elements before sorting: " + aListNumbers); //sort ArrayList in descending order aListNumbers.sort(new DescendingComparator()); System.out.println("ArrayList elements after sorting: " + aListNumbers); } } |
Output
1 2 |
ArrayList elements before sorting: [1, 3, 2, 5, 4] ArrayList elements after sorting: [5, 4, 3, 2, 1] |
Please visit sorting an ArrayList using a Comparator example for more details.
Tip: Instead of passing a reference of a Comparator object, you can also pass null to sort ArrayList elements in a natural order (i.e. ascending for the integer). Condition is, in this case, the elements in the ArrayList must implement the Comparable interface. It works for our example because the Integer class has implemented the Comparable interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(3); aListNumbers.add(2); aListNumbers.add(5); aListNumbers.add(4); System.out.println("ArrayList elements before sorting: " + aListNumbers); /* * You can pass null in the sort method to * sort ArrayList elements in natural order. * * The elements of the ArrayList must implement the * Comparable interface for this to work. */ aListNumbers.sort(null); System.out.println("ArrayList elements after sorting: " + aListNumbers); |
Output
1 2 |
ArrayList elements before sorting: [1, 3, 2, 5, 4] ArrayList elements after sorting: [1, 2, 3, 4, 5] |
Apart from the sort
method of the ArrayList class, you can also use the sort
method of the Collections class to sort ArrayList elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(3); aListNumbers.add(2); aListNumbers.add(5); aListNumbers.add(4); System.out.println("ArrayList elements before sorting: " + aListNumbers); /* * Use the Collections.sort method * to sort the ArrayList elements in * natural order * * The element class must implement * the Comparable interface for this to work. */ Collections.sort(aListNumbers); System.out.println("ArrayList elements after sorting: " + aListNumbers); |
Output
1 2 |
ArrayList elements before sorting: [1, 3, 2, 5, 4] ArrayList elements after sorting: [1, 2, 3, 4, 5] |
Similarly, you can use the custom Comparator to sort the ArrayList elements using an overloaded sort
method of the Collections class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class DescendingComparator implements Comparator<Integer>{ /* * This comparator sorts Integer objects * in descending order */ public int compare(Integer i1, Integer i2) { return i2 - i1; } } public class Example { public static void main(String[] args) { ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(3); aListNumbers.add(2); aListNumbers.add(5); aListNumbers.add(4); System.out.println("ArrayList elements before sorting: " + aListNumbers); /* * Use the Collections.sort method * to sort the ArrayList elements in * order defined by the custom Comparator */ Collections.sort(aListNumbers, new DescendingComparator()); System.out.println("ArrayList elements after sorting: " + aListNumbers); } } |
Output
1 2 |
ArrayList elements before sorting: [1, 3, 2, 5, 4] ArrayList elements after sorting: [5, 4, 3, 2, 1] |
How to synchronize the ArrayList?
The ArrayList class is not a synchronized implementation. That means, if multiple threads are trying to modify the ArrayList structurally like adding or removing elements, the access must be synchronized to avoid unexpected results.
If your application is multi-threaded, you should get the synchronized list wrapper for the ArrayList using the synchronizedList
method of the Collections class as given below.
1 |
List<Integer> list = Collections.synchronizedList( new ArrayList<Integer>() ); |
This method returns a thread-safe (synchronized) List object backed by the original ArrayList. You should use this List object instead of the original ArrayList to make sure that the multi-threaded behavior of your application remains consistent.
How to get the intersection of two ArrayList objects using the retainAll method?
The retainAll
method of the ArrayList class retains only elements that are also present in the specified another ArrayList or Collection object. All the elements that are not present in the specified another list will be removed from this ArrayList (thus creating an intersection of two ArrayList objects).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); //another ArrayList ArrayList<Integer> aListOddNumbers = new ArrayList<Integer>(); aListOddNumbers.add(1); aListOddNumbers.add(3); aListOddNumbers.add(5); /* * To get the intersection of two ArrayList objects, * use the retainAll method. */ //this will retain only elements which are present in the aListOddNumbers aListNumbers.retainAll(aListOddNumbers); System.out.println( "ArrayList intersection: " + aListNumbers ); |
Output
1 |
ArrayList intersection: [1, 3, 5] |
How to check if the ArrayList contains all the elements of another ArrayList using the containsAll method?
The containsAll
method returns true if this ArrayList object contains all the elements of the specified another ArrayList or Collection object. It returns false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
ArrayList<Integer> aListNumbers = new ArrayList<Integer>(); aListNumbers.add(1); aListNumbers.add(2); aListNumbers.add(3); aListNumbers.add(4); aListNumbers.add(5); //another ArrayList ArrayList<Integer> aListOddNumbers = new ArrayList<Integer>(); aListOddNumbers.add(1); aListOddNumbers.add(3); aListOddNumbers.add(5); /* * this will print true, as aListNumbers contains * all the elements of aListOddNumbers * */ System.out.println( aListNumbers.containsAll(aListOddNumbers) ); //add an element to another ArrayList aListOddNumbers.add(7); /* * this will print false, as aListNumbers does not contain * all the elements of aListOddNumbers (7 is missing) * */ System.out.println( aListNumbers.containsAll(aListOddNumbers) ); |
Output
1 2 |
true false |
Below given Java ArrayList examples will help you understand ArrayList concepts in more detail.
Java ArrayList Examples
- What is ArrayList capacity and difference between ArrayList length and capacity
- How to get elements of an ArrayList using the get method
- How to add elements to an ArrayList using the add method
- How to remove elements from ArrayList
- How to print ArrayList elements
- How to get ArrayList length
- Find the minimum or maximum element in ArrayList
- Get first element or last element from ArrayList
- How to compare two ArrayList objects
- Iterate elements of ArrayList using Iterator
- Iterate ArrayList using ListIterator
- Iterate elements of ArrayList using for loop or for each loop
- ArrayList Iterator in Java
- How to get unique elements or values from ArrayList
- How to create ArrayList of arrays, iterate ArrayList of arrays
- How to add array to ArrayList
- Reverse ArrayList
- Get sublist from ArrayList
- How to get random elements from ArrayList
- Shuffle elements of ArrayList
- How to find elements inside ArrayList using indexOf and lastIndexOf methods
- How to binary search elements in ArrayList
- How to replace elements in ArrayList at the given index
- How to clone ArrayList (make a copy of ArrayList)
- How to insert elements at the beginning of ArrayList (at the front)
- Copy elements of ArrayList to another ArrayList object
- How to remove the last element from ArrayList
- How to check if ArrayList is empty
- How to check if ArrayList contains element or value
- How to empty ArrayList (clear ArrayList, remove all elements)
- How to initialize ArrayList with elements
- How to remove duplicate elements from ArrayList
- How to iterate ArrayList in reverse order or backward direction
- Iterate through ArrayList
- How to Sort elements of ArrayList using Comparator
ArrayList conversions examples
- Convert ArrayList to array
- Convert array to ArrayList
- Convert ArrayList to comma separated String
- Convert ArrayList to String array
- Convert comma separated String to ArrayList
- Convert ArrayList to HashSet or TreeSet
- Convert String to ArrayList
- How to convert HashMap keys to ArrayList or HashMap values to ArrayList
- Convert ArrayList to String
- Convert String array to ArrayList
References:
ArrayList Javadoc
Please let me know if you liked the Java ArrayList tutorial with examples in the comments section below.