ArrayList is a resizable array in java. Unlike arrays, there is no size limit for ArrayList. ArrayList adjusts it’s capacity automatically while adding or removing the objects at runtime. Hence it is known as a dynamic array. ArrayList is a class that extends AbstractList and implements List interface.
The Behavior of ArrayList:
- ArrayList maintains insertion order.
- ArrayList allows to store and maintain duplicate values.
- Unlike arrays, ArrayList allows us to store heterogeneous values.
- We cannot use ArrayList for primitive data types.
ArrayList Constructors:
//Constructor to initilize empty ArrayList ArrayList list = new ArrayList(); //Constructor to initilize ArrayList with capacity ArrayList list = new ArrayList(int capacity); //Constructor to initilize ArrayList with elements from collection ArrayList list = new ArrayList(Collection c);
Methods of ArrayList:
Addelements to ArrayList :
by using add() method we can add single elements to ArrayList
import java.util.ArrayList; public class ArrayListImpl { public static void main(String[] args) { //create List with ArrayList class ArrayList numbersList = new ArrayList<>(); //Ading elements to list numbersList.add("One"); numbersList.add("Two"); numbersList.add("Three"); numbersList.add("Four"); //Printing the elements in ArrayList System.out.println("List values: "+numbersList); } }
output:
List values: [One, Two, Three, Four]
Add elements of ArrayList to another ArrayList:
By using the addAll() method we can add all elements of an array list to another array list.
import java.util.ArrayList; public class ArrayListImpl { public static void main(String[] args) { //create List with ArrayList class ArrayList numbersList1 = new ArrayList<>(); //Ading elements to list numbersList1.add("One"); numbersList1.add("Two"); numbersList1.add("Three"); numbersList1.add("Four"); //Printing the elements in numbersList1 System.out.println("List values: "+numbersList1); ArrayList numbersList2 = new ArrayList<>(); numbersList2.add("Five"); numbersList2.add("Six"); //Adding all elements of numbersList2 to numbersList1 numbersList2.addAll(numbersList1); //Printing the elements in numbersList2 after adding numbersList1 System.out.println("List values: "+numbersList2); } }
Output:
List values: [One, Two, Three, Four]
List values: [Five, Six, One, Two, Three, Four]
Access elements of an ArrayList:
By using get() method we can access elements of the array list. we have to pass the index of the element as a parameter.
import java.util.ArrayList; public class ArrayListImpl { public static void main(String[] args) { //create List with ArrayList class ArrayList numbersList1 = new ArrayList<>(); //Ading elements to list numbersList1.add("One"); numbersList1.add("Two"); numbersList1.add("Three"); numbersList1.add("Four"); //Access elements using add method String str = numbersList1.get(0); //Printing the element from numbersList1 System.out.println("Value is: "+str); } }
Output:
Value is: One