ArrayList in Java

Published by Vignesh M on

ArrayList is one of the implementation of the List interface. It is internally a resizable-array under the hood. ArrayList is equivalent to Vector but the only difference is it is not synchronized.

  • ArrayList uses Array internally to store the data. Hence as like Array, random access is possible and it is very fast. The operation is O(1) constant time complexity.
  • Other operations like add, remove is O(N) linear time complexity approximately.

  • For remove operation, ArrayList is not so efficient since the elements has to be shifted in this case. For example, if the 1st element in the list is removed then all other elements has to be shifted by one position and this operation is O(N) complexity. Hence if there is a need for lot of remove operations, LinkedList is better suited for this purpose.
  • ArrayList supports other operations like size(), isEmpty(), sort(), toArray().

Capacity re-allocation when adding elements

Since ArrayList is a re-sizable array, if the capacity of the Array reaches the maximum a new Array is created and elements are copied to new Array. So in general, if the number of elements to be stored is known ahead it’s better to initialize the ArrayList using the size itself.

For example, if 200 items to be stored in list, then

List<String> names = new ArrayList<String>(200);
so that an Array is created with initial capacity of 200.

Summary

ArrayList is a good choice, when

  • The elements are going to be added and retrieved using the random index value. It is O(1) complexity.
  • The applications don’t need to remove the elements which are added.
  • You have to avoid the hassle of creating a new Array and copy the elements into it.

ArrayList is not so efficient, when

  • There is lot of remove operations to be performed. This operation is O(N) time complexity.
  • There is a need to synchronize the operations for concurrent access. Since ArrayList is not designed to be thread safe.

 


Vignesh M

Java developer , AWS Certified Solutions Architect Associate and Cloud technology enthusiast. Currently working for Hexaware technologies. He believes that knowledge increases by sharing not by saving.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.