Java ArrayList
The ArrayList class is a resizable array in the java.util package. There is a difference between a built-in array and an ArrayList in Java. The size of an array cannot be modified to add or remove elements to/from an array to create a new one. While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:
Example
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // This is import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // This is create an ArrayList object
If you are not gather much knowlodge what a package is, read our Java Packages Tutorial.
Add Items
To add an items, the ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method:
Example
import java.util.ArrayList; public class Main { public static void main (String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add("Babita"); names.add("Mamita"); names.add("Kabita"); names.add("Cabita"); names.add("Rabita"); System.out.println(names); } }
Access an Item
To access an element in the ArrayList need to use the get() method and refer to the index number:
Example
names.get(0);
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Item
In order to modify an element, use the set() method and refer to the index number:
Example
names.set(0, “Jarite”);
Remove an Item
In order to remove an element, use the remove() method and refer to the index number:
Example
names.remove(0);
To remove all the elements in the ArrayList, use the clear() method:
Example
names.clear();
ArrayList Size
In order to find out how many elements an ArrayList have, use the size method:
Example
names.size();
Loop Through an ArrayList
Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:
Example
public class ExampleMain { public static void main(String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add("Babita"); names.add("Mamita"); names.add("Kabita"); names.add("Cabita"); names.add("Rabita"); for (int i = 0; i < names.size(); i++) { System.out.println(names.get(i)); } } }
You can also loop through an ArrayList with the for-each loop:
Example
public class Main { public static void main(String[] args) { ArrayList<String> names = new ArrayList<String>(); names.add("Babita"); names.add("Mamita"); names.add("Kabita"); names.add("Cabita"); names.add("Rabita"); for (String i : names) { System.out.println(i); } } }
Other Types
Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type “String”. Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:
Example
Create an ArrayList to store numbers (add elements of type Integer):
import java.util.ArrayList; public class ExampleMain { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(10); myNumbers.add(15); myNumbers.add(20); myNumbers.add(25); for (int i : myNumbers) { System.out.println(i); } } }
Sort an ArrayList
Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:
Example: Sort an ArrayList of Strings:
import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); names.add("Babita"); names.add("Mamita"); names.add("Kabita"); names.add("Cabita"); names.add("Rabita"); Collections.sort(names); // Sort cars for (String i : names) { System.out.println(i); } } }
Example
Sort an ArrayList of Integers:
import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(33); myNumbers.add(15); myNumbers.add(20); myNumbers.add(34); myNumbers.add(8); myNumbers.add(12); Collections.sort(myNumbers); // Sort myNumbers for (int i : myNumbers) { System.out.println(i); } } }
Java ArrayList class hierarchy:
Java ArrayList class uses a dynamic array for storing the elements. It is simila to an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of List interface here. The ArrayList maintains the insertion order internally. It inherits the AbstractList class and implements List interface.
The important points about ArrayList are:
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList class is non synchronized.
- Java ArrayList allows random access because array works at the index basis.
In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let’s see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Constructors of ArrayList, Constructor with Description BELOW
- ArrayList() : It is used to build an empty array list.
- ArrayList(Collection<? extends E> c): It is used to build an array list that is initialized with the elements of the collection c.
- ArrayList(int capacity): It is used to build an array list that has the specified initial capacity.
Methods of ArrayList | Method Description |
void add(int index, E element) | It is used to insert the specified element at the specified position in a list. |
boolean add(E e) | It is used to append the specified element at the end of a list. |
boolean addAll(Collection<? extends E> c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator. |
boolean addAll(int index, Collection<? extends E> c) | It is used to append all the elements in the specified collection, starting at the specified position of the list. |
void clear() | It is used to remove all of the elements from this list. |
void ensureCapacity(int requiredCapacity) | It is used to enhance the capacity of an ArrayList instance. |
E get(int index) | It is used to fetch the element from the particular position of the list. |
boolean isEmpty() | It returns true if the list is empty, otherwise false. |
Iterator() | It works to traverse collection. |
listIterator() | It works to traverse collection or list. |
int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. |
Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order. |
<T> T[] toArray(T[] a) | It is used to return an array containing all of the elements in this list in the correct order. |
Object clone() | It is used to return a shallow copy of an ArrayList. |
boolean contains(Object o) | It returns true if the list contains the specified element |
int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. |
E remove(int index) | It is used to remove the element present at the specified position in the list. |
boolean remove(Object o) | It is used to remove the first occurrence of the specified element. |
boolean removeAll(Collection<?> c) | It is used to remove all the elements from the list. |
boolean removeIf(Predicate<? super E> filter) | It is used to remove all the elements from the list that satisfies the given predicate. |
protected void removeRange(int fromIndex, int toIndex) | It is used to remove all the elements lies within the given range. |
void replaceAll(UnaryOperator<E> operator) | It is used to replace all the elements from the list with the specified element. |
void retainAll(Collection<?> c) | It is used to retain all the elements in the list that are present in the specified collection. |
E set(int index, E element) | It is used to replace the specified element in the list, present at the specified position. |
void sort(Comparator<? super E> c) | It is used to sort the elements of the list on the basis of specified comparator. |
Spliterator<E> spliterator() | It is used to create spliterator over the elements in a list. |
List<E> subList(int fromIndex, int toIndex) | It is used to fetch all the elements lies within the given range. |
int size() | It is used to return the number of elements present in the list. |
void trimToSize() | It is used to trim the capacity of this ArrayList instance to be the list’s current size. |
void add(int index, E element) | It is used to insert the specified element at the specified position in a list. |
Java Non-generic Vs. Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.
Old non-generic example of creating java collection.
ArrayList list=new ArrayList();//creating old non-generic arraylist. New generic example of creating java collection.
ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.
Java ArrayList Example
import java.util.*; public class ArrayListExample1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); //Printing the arraylist object System.out.println(list); } }
Test it Now
Output:
[Man, Cat, Banana, Cow]
Iterating ArrayList using Iterator
Let’s see another example to traverse ArrayList elements using the Iterator interface.
import java.util.*; public class ArrayListExample2{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); //Traversing list through Iterator Iterator itr=list.iterator();//getting the Iterator while(itr.hasNext()){//check if iterator has the elements System.out.println(itr.next());//printing the element and move to next } } }
Output:
Man
Cat
Banana
Cow
Iterating ArrayList using For-each loop
Let’s see another example to traverse the ArrayList elements using the for-each loop
import java.util.*; public class ArrayListExample3{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); //Traversing list through for-each loop for(String fruit:list) System.out.println(fruit); } }
Output:
Man
Cat
Banana
Cow
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set() method changes the element.
import java.util.*; public class ArrayListExample4{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); //accessing the element System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0 //changing the element list.set(1,"Dates"); //Traversing list for(String lives:list) System.out.println(lives); } }
Output:
Returning element:
Man
Cat
Banana
Cow
How to Sort ArrayList
The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*; class SortArrayList{ public static void main(String args[]){ //Creating a list of fruits List<String> list1=new ArrayList<String>(); list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); //Sorting the list Collections.sort(list1); //Traversing list through the for-each loop for(String lives:list1) System.out.println(lives); System.out.println("Sorting numbers..."); //Creating a list of numbers List<Integer> list2=new ArrayList<Integer>(); list2.add(12); list2.add(11); list2.add(10); list2.add(9); //Sorting the list Collections.sort(list2); //Traversing list through the for-each loop for(Integer number:list2) System.out.println(number); } }
Output:
Man
Cat
Banana
Cow
Sorting numbers…
9
10
11
12
Ways to iterate the elements of the collection in Java:
There are various ways to traverse the collection elements. By Iterator interface, for-each loop, ListIterator interface, for loop,forEach() and forEachRemaining() method. Let’s see an example to traverse the ArrayList elements through other ways
import java.util.*; class ArrayList4{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Man");//Adding object in arraylist list.add("Cat"); list.add("Banana"); list.add("Cow"); System.out.println("Traversing list through List Iterator:"); //Here, element iterates in reverse order ListIterator<String> list1=list.listIterator(list.size()); while(list1.hasPrevious()) { String str=list1.previous(); System.out.println(str); } System.out.println("Traversing list through for loop:"); for(int i=0;i<list.size();i++) { System.out.println(list.get(i)); } System.out.println("Traversing list through forEach() method:"); //The forEach() method is a new feature, introduced in Java 8. list.forEach(a->{ //Here, we are using lambda expression System.out.println(a); }); System.out.println("Traversing list through forEachRemaining() method:"); Iterator<String> itr=list.iterator(); itr.forEachRemaining(a-> //Here, we are using lambda expression { System.out.println(a); }); } }
Output:
Traversing list through List Iterator:
Man
Cat
Banana
Cow
Traversing list through for loop:
Cow
Banana
Cat
Man
Traversing list through forEach() method:
Cow
Banana
Cat
Man
Traversing list through forEachRemaining() method:
Cow
Banana
Cat
Man
User-defined class objects in Java ArrayList
Let’s see an example where we are storing Student class object in an array list.
class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } } import java.util.*; class ArrayList5{ public static void main(String args[]){ //Creating user-defined class objects Student s1=new Student(101,"Harun",20); Student s2=new Student(102,"Md",21); Student s2=new Student(103,"Paru",22); //creating arraylist ArrayList<Student> al=new ArrayList<Student>(); al.add(s1);//adding Student class object al.add(s2); al.add(s3); //Getting Iterator Iterator itr=al.iterator(); //traversing elements of ArrayList object while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } } }
Output:
101 Harun 20
102 Md 21
103 Paru 22
Java ArrayList Serialization and Deserialization Example
Let’s see an example to serialize an ArrayList object and then deserialize it.
import java.io.*; import java.util.*; class ArrayList6 { public static void main(String [] args) { ArrayList<String> list=new ArrayList<String>(); list.add("R"); list.add("V"); list.add("A"); try { //Serialization FileOutputStream foslist=new FileOutputStream("file"); ObjectOutputStream ooslist =new ObjectOutputStream(fos); ooslist.writeObject(list); foslist.close(); ooslist.close(); //Deserialization FileInputStream fislist=new FileInputStream("file"); ObjectInputStream oislist=new ObjectInputStream(fislist); ArrayList alist=(ArrayList)oislist.readObject(); System.out.println(alist); }catch(Exception e) { System.out.println(e); } } }
Output:
[R, V, A]
Java ArrayList example to add elements
Here, example code of different ways to add an element.
import java.util.*; class ArrayList7{ public static void main(String args[]){ ArrayList<String> list =new ArrayList<String>(); System.out.println("Initial list of elements: "+ list); //Adding elements to the end of the list list.add("R"); list.add("V"); list.add("A"); System.out.println("After invoking add(E e) method: "+ list); //Adding an element at the specific position list.add(1, "G"); System.out.println("After invoking add(int index, E element) method: "+al); ArrayList<String> list2=new ArrayList<String>(); list2.add("S"); list2.add("H"); //Adding second list elements to the first list list2.addAll(list2); System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ list); ArrayList<String> list3=new ArrayList<String>(); list3.add("J"); list3.add("R"); //Adding second list elements to the first list at specific position list.addAll(1, list3); System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ list); } }
Output:
Initial list of elements: []
After invoking add(E e) method: [R, V, A]
After invoking add(int index, E element) method: [R, G, V, A]
After invoking addAll(Collection<? extends E> c) method:
[R, G, V, A, S, H]
After invoking addAll(int index, Collection<? extends E> c) method:
[R, J, R, G, V, A, S, H]
Java ArrayList example to remove elements
Here, we see different ways to remove an element.
import java.util.*; class ArrayList8 { public static void main(String [] args) { ArrayList<String> list=new ArrayList<String>(); list.add("R"); list.add("V"); list.add("A"); list.add("A"); list.add("G"); System.out.println("An initial list of elements: "+ list); //Removing specific element from arraylist list.remove("V"); System.out.println("After invoking remove(object) method: "+ list); //Removing element on the basis of specific position list.remove(0); System.out.println("After invoking remove(index) method: "+ list); //Creating another arraylist ArrayList<String> list2=new ArrayList<String>(); list2.add("R"); list2.add("H"); //Adding new elements to arraylist list2.addAll(list2); System.out.println("Updated list : "+ list); //Removing all the new elements from arraylist list.removeAll(list2); System.out.println("After invoking removeAll() method: "+ list); //Removing elements on the basis of specified condition list.removeIf(str -> str.contains("A")); //This is Lambda expression System.out.println("After invoking removeIf() method: "+ list); //Removing all the elements available in the list list.clear(); System.out.println("After invoking clear() method: "+ list); } }
Output:
An initial list of elements: [R, V, A, A, G]
After invoking remove(object) method: [R, A, A, G]
After invoking remove(index) method: [A, A, G]
Updated list : [A, A, G, R, H]
After invoking removeAll() method: [A, A, G]
After invoking removeIf() method: [A, G]
After invoking clear() method: []