212014Sep

ArrayList Class In Java

ArrayList Class In Java:-

ArrayList uses array to store the elements.
It extends AbstractList and implements List, RandomAccess(Marker Interface), Cloneable, Serializable.

Three Constructors are available in ArrayList:-

  1. ArrayList() – Constructs an empty list with an initial capacity of 10.
  2. ArrayList(Collection<? extends E> c) – Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
  3. ArrayList(int initialCapacity) – Constructs an empty list with the specified initial capacity.

Read Popular Interview Question Singleton In Java.

Features of Array List:-

1. Data Structure :- ArrayList is backed Array data structure.

2. Insertion in ArrayList(Time Consuming) :- Arraylist maintains insertion order. ArrayList make a contiguous memory allocation which means ot always first create a space and then insert a value in it. So it require two step for insertion and insertion of any value in ArrayList take more time. So for fast insertion and deletion we never prefer ArrayList.

3. Random access in ArrayList(Fast Access) :– Search any value of ArrayList is fast due to its implementations of RandomAccess(Marker Interface).For Random access we use get(int index) method which find value of searched operation directly, no need to iterate the arraylist that’s why it take less time.
Suppose we search a value from ArrayList based on its index:-

ArrayList al=new ArrayList(1000000);
.
.
.
al.get(1);
al.get(50000);
al.get(10000000);

All operations will take same time to search data and give output.

4. Capacity of ArrayList :- Array list initial capacity is 10. If we want to insert any data when it reaches at maximum capacity internally new array is created with more capacity and elements are copied from old array to new high capacity array.

Till Java 6
New Capacity = (3/2*previous capacity)+1

Since Java 7
New Capacity = oldCapacity + (oldCapacity >> 1);

e.g if it reaches to 10 so oldCapacity=10 then newCapacity will be 15.

5. ArrayList is not Synchronized. But we can convert unsynchronized collection to Sysnchronized but vice versa is not possible.

Conclusion:-

1. We should always use ArrayList for Fast search of the data.

2. Insertion Process is very slow.

3. Intermediate index based based remove and add data is very time consuming process.

Read Load Factor In HashMap.