Site icon Narayana Tutorial

Array List

Array List

Constructors of ArrayList

↔   creates an empty ArrayList object with default intial capacity 10.

↔  If arraylist reaches its max capacity, then a new ArrayList object is created with new capacity .

       New capacity = (current capacity × ³/² ) + 1 = 16

↔  creates an empty ArrayList object, with the specified initial capacity.

↔  creates an equivalent ArrayList object for the given collection object. This constructor is for inter convertion between collection objects.

package com.narayanatutorial.collections;
import java.util.ArrayList;
/**
  * @author narayanatutorial
 */
public class ExonArrayList {
 public static void main(String[] args) {
 ArrayList al = new ArrayList();
 al.add("A");
 al.add(10);
 al.add("A");
 al.add(null);
 System.out.println(al);
 al.remove(2);
 System.out.println(al);
 al.add(2, "M");
 al.add("N");
 System.out.println(al);
 }
}

Note:- 

In general collection objects can be used to store objects and to transport those objects to support this requirement every collection implemented class already implemented Serializable and Cloneable interfaces.

package com.narayanatutorial.collections;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.RandomAccess;
/**
 * @author Narayanatutorial
 */
public class ArrayList {
  public static void main(String args[]){
    ArrayList l1 = new ArrayList ();
    LinkedList l2 = new LinkedList ();
    System.out.println(l1 instanceof Serializable); //false
    System.out.println(l2 instanceof Serializable); //true
    System.out.println(l1 instanceof RandomAccess); //false
    System.out.println(l2 instanceof RandomAccess);//false
    System.out.println(l2 instanceof Cloneable); //true
  }
}
Output
false
true
false
false
true

Que:- What is Random Access & its purpose?

Ans:-  ArrayLsit is not recommended to use, it frequent operation is insertion or deletion in the middle.

Note:- If our frequent operation is insertion / deletion the middle, we can’t use ArrayList. We can handle this requirement by using LinkedList.