Tuesday, December 26, 2017

ArrayList



Arraylist implemented List interface. its having all features which is in List.

Its having the underline data structure  is re sizable array.
Duplicates are allowed.
Insertion order is preserved.
heterogeneous objects allowed.
Null insertion is possible.

constructors:

1.  arraylist l=new Arraylist();

above array list is empty and default initial capacity is 10.
Once arraylist reaches max capacity then new arraylist object will be creates with new capacity

like new capacity=(current capacity*3/2)+1

2. arraylist l1=new arrayList(int initial capacity)

 creates an empty arraylist object with specifies initial capacity.

3. Arraylist l3=new Arraylist(Collection c);

Creates am equivalent Arraylst object for given Collection.


Example:

package indrajeet.list.exp;
import java.util.*;

class ArrayListdemo{
public static void main(String args[]){

ArrayList l=new ArrayList();

   l.add("A");
   l.add(10);
   l.add(null);
   l.add("A");
 System.out.println(l);

}
}

output:  [A, 10, null, A]



ArrayList and Vector classes implements RandomAccess  interface so that ArrayList can access random elements. We can access with the same speed..

ArrayList is the best choice if our frequent operation is retrial operation(because its implements RandomAccess interface).
ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle( because more shifting required).


By using array[index], you can access to any element while in a linked list you must navigate through all the list starting from fist until you get the element which you need.

access time for arrayList O(1)
   LinkedList O(n)