The ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.
Note:
- ArrayList provides the facility of random access because it is index-based.
- A lot of shifting needs to occur if any element is removed from the array list. Thus, manipulation is slow in the Java ArrayList class.
ArrayList class declaration:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Java ArrayList Constructors:
Constructor | Description |
ArrayList() | It will create an empty array list. |
ArrayList(Collection<? extends E> c) | It will create an array list that is initialized with the elements of the collection c. |
ArrayList(int capacity) | It will create an array list that has the specified initial capacity. |
Java ArrayList Methods:
Method | Description |
void add(int index, E element) | It will insert the specified element at the specified position in a list. |
boolean add(E e) | It will append the specified element at the end of a list. |
boolean addAll(Collection<? extends E> c) | It will append all of the elements in the specified collection to the end of the current list, in the order that they are returned by the specified collection’s iterator. |
boolean addAll(int index, Collection<? extends E> c) | It will append all the elements in the specified collection, starting at the specified position of the list. |
void clear() | It will remove all of the elements from the current list. |
void ensureCapacity(int requiredCapacity) | It will enhance the capacity of an ArrayList instance. |
E get(int index) | It will fetch the element from the specified position of the list. |
boolean isEmpty() | It will return true if the list is empty, otherwise, return false. |
int lastIndexOf(Object o) | It will return the index from the list of the last occurrence of the specified element, or -1 if the list does not contain this element. |
Object[] toArray() | It will return an array containing all of the elements in the specified list in the correct order. |
<T> T[] toArray(T[] a) | It will return an array containing all of the elements in the specified list in the correct order. |
Object clone() | It will return a shallow copy of the specified ArrayList. |
boolean contains(Object o) | It will return true if the current list contains the specified element. |
int indexOf(Object o) | It will return the index from the list of the first occurrence of the specified element, or -1 if the List does not contain this element. |
E remove(int index) | It will eliminate or remove the element present at the specified position in the list. |
boolean remove(Object o) | It will eliminate or remove the first occurrence of the specified element. |
boolean removeAll(Collection<?> c) | It will eliminate or remove all the elements from the list. |
boolean removeIf(Predicate<? super E> filter) | It will eliminate or remove all the elements from the list that satisfies the given predicate or condition. |
protected void removeRange(int fromIndex, int toIndex) | It will eliminate all the elements that lie within the given range i.e. fromIndex – toIndex. |
void replaceAll(UnaryOperator<E> operator) | It will replace all the elements from the list with the specified element. |
void retainAll(Collection<?> c) | It will retain all the elements in the list that are present in the specified collection. |
E set(int index, E element) | It will replace the specified element in the list, present at the specified position. |
void sort(Comparator<? super E> c) | It will sort the elements of the current list on the basis of the specified comparator. |
Spliterator<E> spliterator() | It will create spliterator over the elements in a list. |
List<E> subList(int fromIndex, int toIndex) | It will fetch all the elements that lie within the given range. |
int size() | It will return the number of elements present in the list. |
void trimToSize() | It will trim the capacity of this ArrayList instance to be the list’s current size. |
Java Non-generic Vs. Generic Collection:
Before JDK 1.5, the Java collection framework was non-generic. It becomes generic with JDK 1.5. Only one type of object is allowed in a collection by the Java new generic collection. Typecasting is not required at runtime, because it is type-safe.
The old non-generic approach to create a java collection:
ArrayList al=new ArrayList();
A new generic approach to create a java collection:
ArrayList<String> al=new ArrayList<String>();
The type is specified in angular braces in a generic collection. Thus, the ArrayList will be forced to have the only specified type of objects in it and will give a compile-time error, when another type of object is added.
ArrayList example:
ArrayListSetTest.java
import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This class is used to show the ArrayList functionality. * @author w3spoint */ public class ArrayListTest { public static void main(String args[]){ //Create ArrayList object. List arrayList = new ArrayList(); //Add objects to the HashSet. arrayList.add("Amani"); arrayList.add("Prabhjot"); arrayList.add("Nidhi"); arrayList.add("Vandana"); arrayList.add("Poonam"); //Size of the ArrayList object. System.out.println("Size: " + arrayList.size()); //Print the ArrayList object. System.out.println("ArrayList elements:"); System.out.println(arrayList); //Print the ArrayList elements using iterator. Iterator iterator1=arrayList.iterator(); System.out.println("ArrayList elements " + "using iterator:"); while(iterator1.hasNext()){ System.out.println(iterator1.next()); } //Add an object at the specific position. arrayList.add(2,"Jagdeep"); //Remove a element from a specific position. arrayList.remove(3); arrayList.remove(4); //Size of the ArrayList object. System.out.println("Size after manipulation: " + arrayList.size()); //Print the ArrayList object. System.out.println("ArrayList elements" + " after manipulation:"); System.out.println(arrayList); //Print the ArrayList elements using iterator. Iterator iterator2=arrayList.iterator(); System.out.println("ArrayList elements after" + " manipulation using iterator:"); while(iterator2.hasNext()){ System.out.println(iterator2.next()); } } } |
Output:
Size: 5 ArrayList elements: [Amani, Prabhjot, Nidhi, Vandana, Poonam] ArrayList elements using iterator: Amani Prabhjot Nidhi Vandana Poonam Size after manipulation: 4 ArrayList elements after manipulation: [Amani, Prabhjot, Jagdeep, Vandana] ArrayList elements after manipulation using iterator: Amani Prabhjot Jagdeep Vandana |
To iterate the elements of the collection in java:
To traverse the collection elements, there are various ways :
- By using the Iterator interface.
- By using for-each loop.
- By using the ListIterator interface.
- By using fusing or loop.
- By using forEach() method.
- By using forEachRemaining() method.
Example: To traverse ArrayList elements using the Iterator interface:
import java.util.*; public class ArrayListExample{ public static void main(String args[]){ //Creating arraylist object ArrayList<string> list=new ArrayList<string>(); //Adding object in arraylist list.add("A"); list.add("B"); list.add("A"); list.add("C"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } |
Output:
Example: To traverse the ArrayList elements using the for-each loop:
import java.util.*; public class ArrayListExample{ public static void main(String args[]){ ArrayList<string> al=new ArrayList<string>(); al.add("A"); al.add("B"); al.add("A"); al.add("C"); //Traversing list through for-each loop for(String obj:al) System.out.println(obj); } } |
Output:
Example: To traverse the ArrayList elements through other ways:
import java.util.*; public class ArrayListExample{ public static void main(String args[]){ //Creating arraylist object ArrayList<string> list=new ArrayList<string>(); //Adding object in arraylist list.add("A"); list.add("B"); list.add("A"); list.add("C"); System.out.println("Traversing list through List Iterator:"); //Arraylist elements 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 using forEach() method:"); //Using forEach() method of Java 8. list.forEach(a->{ System.out.println(a); }); System.out.println("Traversing list using forEachRemaining() method:"); Iterator<string> itr=list.iterator(); itr.forEachRemaining(a-> { System.out.println(a); }); } } |
Output:
Java ArrayList with User-defined class objects:
Example:
import java.util.*; class Employee{ int id; String name; int age; Employee(int id,String name,int age){ this.id=id; this.name=name; this.age=age; } } public class ArrayListExample{ public static void main(String args[]){ //Creating user-defined class objects Employee e1=new Employee(1,"Tom",33); Employee e2=new Employee(2,"Jerry",40); Employee e3=new Employee(3,"John",45); //creating arraylist object ArrayList<employee> al=new ArrayList<employee>(); //Adding Employee class object al.add(e1); al.add(e2); al.add(e3); //Get Iterator object Iterator itr=al.iterator(); /Traversing elements of ArrayList object while(itr.hasNext()){ Employee emp=(Employee)itr.next(); System.out.println(emp.id+" "+emp.name+" "+emp.age); } } } |
Output:
Explanation:
In the above example, we are storing the Employee class objects in an array list.
Java ArrayList Serialization and Deserialization:
Example: To serialize an ArrayList object and then deserialize it:
import java.io.*; import java.util.*; public class ArrayListExample{ public static void main(String [] args) { ArrayList<string> al=new ArrayList<string>(); al.add("A"); al.add("B"); al.add("C"); try { //Serialization FileOutputStream fos=new FileOutputStream("file"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(al); fos.close(); oos.close(); //Deserialization FileInputStream fis=new FileInputStream("file"); ObjectInputStream ois=new ObjectInputStream(fis); ArrayList list=(ArrayList)ois.readObject(); System.out.println(list); }catch(Exception e) { System.out.println(e); } } } |
Output:
Add elements in ArrayList:
Example: To add an element in different ways:
import java.util.*; public class ArrayListExample{ public static void main(String args[]){ ArrayList<string> al=new ArrayList<string>(); System.out.println("Initial list of elements: "+al); //Adding elements to the end of the list al.add("A"); al.add("B"); al.add("C"); System.out.println("After invoking add(E e) method: "+al); //Adding an element at the specific position al.add(1, "abc"); System.out.println("After invoking add(int index, E element) method: "+al); ArrayList<string> al2=new ArrayList<string>(); al2.add("def"); al2.add("ghi"); //Adding second list elements to the first list al.addAll(al2); System.out.println("After invoking addAll(Collection<? extends E> c) method: "+al); ArrayList<string> al3=new ArrayList<string>(); al3.add("uvw"); al3.add("xyz"); //Adding second list elements to the first list at specific position al.addAll(1, al3); System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+al); } } </string> |
Output:
Remove elements from ArrayList:
Example: To remove an element in different ways:
import java.util.*; public class ArrayListExample{ public static void main(String [] args) { ArrayList<string> al=new ArrayList<string>(); al.add("A"); al.add("B"); al.add("C"); al.add("D"); al.add("E"); System.out.println("An initial list of elements: "+al); //Removing specific element from arraylist al.remove("B"); System.out.println("After invoking remove(object) method: "+al); //Removing element on the basis of specific position al.remove(0); System.out.println("After invoking remove(index) method: "+al); //Creating another ArrayList ArrayList<string> al2=new ArrayList<string>(); al2.add("A"); al2.add("F"); //Adding new elements to arraylist al.addAll(al2); System.out.println("Updated list : "+al); //Removing all the new elements from arraylist al.removeAll(al2); System.out.println("After invoking removeAll() method: "+al); //Removing elements on the basis of specified condition al.removeIf(str -> str.contains("C")); System.out.println("After invoking removeIf() method: "+al); //Removing all the elements available in the list al.clear(); System.out.println("After invoking clear() method: "+al); } } </string> |
Output:
retainAll() method:
Example:
import java.util.*; public class ArrayListExample{ public static void main(String args[]){ ArrayList<string> al=new ArrayList<string>(); al.add("A"); al.add("B"); al.add("C"); ArrayList<string> al2=new ArrayList<string>(); al2.add("A"); al2.add("D"); al.retainAll(al2); System.out.println("iterating the elements after retaining the elements of al2"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } </string> |
Output:
isEmpty() method:
Example:
import java.util.*; public class ArrayListExample{ public static void main(String [] args) { ArrayList<string> al=new ArrayList<string>(); System.out.println("Is ArrayList Empty: "+al.isEmpty()); al.add("A"); al.add("B"); al.add("C"); System.out.println("After Insertion"); System.out.println("Is ArrayList Empty: "+al.isEmpty()); } } </string> |
Output:
set() and get() method:
Example:
import java.util.*; public class ArrayListExample{ public static void main(String [] args) { ArrayList<string> al=new ArrayList<string>(); al.add("A"); al.add("B"); al.add("C"); System.out.println("Before update: "+al.get(1)); //Updating an element at specific position al.set(1,"D"); System.out.println("After update: "+al.get(1)); } } </string> |
Output: