Java ArrayList

Java ArrayList

ArrayList In Java 
Standard arrays are of a fixed length in Java. hence after the creation of the array they cannot be grown, or shrank in size hence one must decide how many number should be in the array. To make it dynamic we use arrayList which is found in Collection framework Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements the List interface.
The important points about the Java ArrayList class are -
  • Java ArrayList class is non synchronized.
  •  Java ArrayList allows random access because the array works on the basis of index.
  •  Java ArrayList class can contain duplicate elements.
  • Manipulation of elements is slow because a lot of shifting needs to happen after the removal of any element in arraylist.
import java.util.*;
// Or import java.util.ArayList;
ArrayList list=new ArrayList();  
Now we will see the use and example of methods 
  • size(), which is used to identify the size of ArrayList, and 
  • add() which is used to add a new element in ArrayList, and 
  • set() which is used to change the existing element in ArrayList., and 
  • get() to access the elements in ArrayList And at Last 
  • remove() to remove the elements.
Example -  
package javaLearnings;

import java.util.ArrayList;

public class Main {

  public static void main(String args[]) {
      // Create an array list.
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " +
// Add elements to the array list.
      al.add(1, 67);
      System.out.println("Size of al after additions: " +
// Display the array list.
      System.out.println("Contents of al: " + al);
// Set a element
      al.set(2, 5);

// get a element in ArrayList
// Remove elements from the array list.
      System.out.println("Size of al after deletions: " +
      System.out.println("Contents of al: " + al);

Output -