How to create an Array List with Java?

To store dynamically-sized elements in Java, we used ArrayList. Whenever new elements are added to it, its increase their size automatically.

Key Points of an ArrayList

  1. An ArrayList is a re-sizable array, also known as a dynamic array. It raises its size according to new elements and decreases the size when the elements are removed.
  2. An array is used to store an element in ArrayList internally. It allows you to retrieve the elements by their index.
  3. Java ArrayList class permits duplicate and null values.
  4. Java ArrayList class is a well-ordered collection. It keeps the insertion order of the elements.
  5. In ArrayList, you cannot create an ArrayList of primitive types like int, char, boolean, etc. You must use boxed types like Integer, Character, Boolean etc.

Let’s create an ArrayList

Using Java we could easily create an ArrayList object:

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

In this example, list is of “String” type, the elements are that going to be added to this list will be string type. The type decide which type of elements list will have.

How to add new elements to ArrayList?

To add an element in ArrayList, we can use add() method. This method has variations, which is use depends on requirements.




class ArrayListExample { 
   public static void main(String args[]){ 
      ArrayList<String> arrayList = ArrayList<String>(); 
      //Adding "Tom" at the third position
      arrayList.add(3, "Tom");
      //displaying elements


Leave a Reply

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