Array List

Array List

  • The underlying  data structure is resizeable Array or growable Array.
  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • Hetrogenious objects are allowed.
  • Null insertion is possible.

Constructors of ArrayList

  • ArrayList l = new 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

  • ArrayList l = new ArrayList ( int initial capacity)

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

  • ***** ArrayList l = new ArrayList ( collection c )

↔  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.

  • ArrayList and vector classes implements Random Access interface, hence we can access any random element with the same speed, hence  if frequent operation is retrieval then it is recommended to use ArrayList.
  • Random Access interface present in java.util package & does’t contain any methods. it is a marker interface.
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.

 

Leave a Reply