ArrayList Class In Java Collection Framework

ArrayList(under java.util package) is one of the most widely used Collection class in Java. ArrayList underlying data structure is re-sizable Array (Grow-able Array). As ArrayList implements List interface, so duplicates are allowed in ArrayList and insertion order is preserved. If we are not using generic implementation of ArrayList then Heterogeneous objects are allowed in ArrayList. (Note: Except TreeSet and TreeMap every where in Collection Framework Heterogeneous objects are allowed for non generic concrete implementation class) Null insertion is also possible in ArrayList.

ArrayList class implements List, RandomAccess, Cloneable, Serializable interfaces  and extends AbstractList class. Let see the ArrayList class declaration:

 

ArrayList Constructors

 

 Constructor Description
ArrayList() It is used to build an empty array list with default initial capacity 10. Example:

ArrayList list = new ArrayList();

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the collection c.

 

ArrayList list = new ArrayList(), creates an empty ArrayList with default initial  capacity 10. Once ArrayList reaches its maximum capacity, a new ArrayList will be created with

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

ArrayList Methods

Methods Description
public boolean add(E e) Appends the specified element to the end of this list.
public void add(int index, E element)  Inserts the specified element at the specified position in this list.
public void addAll(int index, Collection<? extends E> c)  Inserts all of the elements in the specified collection into this list, starting at the specified position.
 public void clear()  Removes all of the elements from this list.
 public boolean contains(Object o)  Returns true if this list contains the specified element.
 public Object clone()  Returns a shallow copy of this ArrayList instance.
 public void ensureCapacity(int minCapacity)  Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
 public void forEach(Consumer<? super E> action)  Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
 public E get(int index)  Returns the element at the specified position in this list.
 public boolean isEmpty()  Returns true if this list contains no elements.
 public int indexOf(Object o)  Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
 public Iterator<E> iterator()  Returns an iterator over the elements in this list in proper sequence.The returned iterator is fail-fast.
 public int lastIndexOf(Object o)  Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
 public ListIterator<E> listIterator()  Returns a list iterator over the elements in this list (in proper sequence). The returned list iterator is fail-fast.
 public ListIterator<E> listIterator(int index)  Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
public E remove(int index) Removes the element at the specified position in this list.
public boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. If the element is not present in the list, it is unchanged.
public boolean removeAll(Collection<E> c) Removes from this list all of its elements that are contained in the specified collection.
public boolean retainAll(Collection<E> c) Retains only the elements in this list that are contained in the specified collection.
protected void removeRange(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
public boolean retainAll(Collection<?> c) Replaces each element of this list with the result of applying the operator to that element.
 public boolean removeIf(Predicate<? super E> filter)  Removes all of the elements of this collection that satisfy the given predicate.
 public void replaceAll(UnaryOperator<E> operator)  Replaces each element of this list with the result of applying the operator to that element.
public int size() Returns the number of elements in this list.
public E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
public List<E> subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
public Spliterator<E> spliterator() Creates a late binding and fail-fast Spliterator over the elements in this list.
public void sort(Comparator<? super E> c) Sorts this list according to the order induced by the specified Comparator.
public void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.
public Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
public <T> T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

 

                  Non-generic ArrayList Vs Generic ArrayList Collection

Java collection framework was non-generic before JDK 1.5. Afterward version it is generic now. Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.

Non-generic ArrayList

Generic ArrayList

//creating non-generic ArrayList

ArrayList list=new ArrayList();

//creating generic ArrayList

ArrayList<String> list=new ArrayList<String>();

It is not type safe so typecasting is required at run time, If we add objects of different types. ArrayList  as generic collection, is forced to have only specified type of objects in it, so it is type safe. If you try to add another type of object, it will give compile time error.

 

Note: ArrayList & Vector classes implements RandomAccess Interface(present in java.util package) , which is Marker Interface as it doesn’t contain any method, so that we can access any random element with the same speed. So getting  5000th element present in a particular list will take same time as getting 1st element in the list.

 

Note:

  1. ArrayList is the best choice, if your frequent operation is retrieval operation because ArrayList implements RandomAccess Interface.
  2. ArrayList is the worst choice, if your frequent operation is insertion or deletion operation in the middle because in that case several shift operations will be required internally.

Difference Between ArrayList and Vector

ArrayList Vector
Every method present in ArrayList is non synchronized Every method present in Vector is synchronized
At a time mutiple threads are allowed to operate on ArrayList and hence ArrayList is not thread safe At a time only one thread is allowed to operate on Vector and hence Vector is thread safe
Threads are not required to wait to operate on ArrayList object and hence relatively performance is high Threads are required to wait to operate on Vector object and hence relatively performance is low.
Introduced in Java 1.2 version Introduced in Java 1.0 version and it is a Legacy class

 

How we can get synchronized ArrayList object in Java?

Note: This question can be asked by any interviewer in initial round java interview. By default ArrayList object is non synchronized, but we can get synchronized version of ArrayList by using Collections Utility class synchronizedList() static method. Below is the method declaration:

static <T> List<T> synchronizedList(<List<T> list) Returns a synchronized (thread-safe) collection backed by the specified collection.

 

Similarly we can get synchronized version of Set, Map objects by using following methods of Collections Utility class.

static <T> Set<T> synchronizedSet(<Set<T> set) Returns a synchronized (thread-safe) set backed by the specified set.
static <K,V> Map<K,V> synchronizedMap(<Map<K,V> map) Returns a synchronized (thread-safe) map backed by the specified map.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *