Java ArrayList

Posted in Java Collections By Raj On November 18, 2017


The difference between Array and ArrayList is, in Array we can store fixed set of elements which means once arrays are created you cannot change length, but an ArrayList is not like that and it is resizable and it grows on-demand basis, when you add new elements to an ArrayList it will automatically resize 

  • Java ArrayList can dynamically increase or decrease in size
  • Java ArrayList can have duplicate values
  • Java ArrayList allows null values
  • The initial capacity of Java ArrayList is 10 if you are using Java 8 then it is zero
  • You can specify initial capacity while creating Java ArrayList using ArrayList constructor
  • Java ArrayList is not thread safe so in multithreading environment, you need to take care
  • Java ArrayList supports Generics
  • When elements are removed from ArrayList the size will automatically reduce
  • You can trim the ArrayList capacity to list’s current size by calling trimToSize() method to minimize the storage of Java ArrayList instance

Important things to consider

  • If you are planning to do lot of manipulations on ArrayList something like removing elements based on index’s or adding some elements will require element’s shifting which may impact’s on performance so, better to avoid ArrayList if you have lot of manipulations, instead of that you can use LinkedList
  • You can not get the previous element value in ArrayList but you can get it using LinkedList

Java ArrayList Constructors

The Java ArrayList has the following constructors

ArrayList( )

  • This is the default constructor and most of the people use this, when you create an ArrayList using this, before Java  version’s the initial capacity is allocated to 10 but, in Java 8 the capacity is allocated zero

ArrayList(int capacity)

  • If you know how many elements you are going to store and you don’t want to recreate ArrayList when the capacity is reached then you can use this 

ArrayList(Collection<? extends E> c)

  • If you want to create an ArrayList with the specified collection then you can use this

ArrayList Example :

The following example shows a simple use of ArrayList, the ArrayList is created using string objects

Output :

If you are looking for more examples on ArrayList then refer this ArrayList Code Snippets