Java ArrayList : Collection Class



ArrayList class :

  1. ArrayList is used to dynamic array of the elements.
  2. ArrayList allows duplicate elements in it.
  3. ArrayList class extends AbstractList class and implements List interface.
  4. ArrayList maintains insertion order.
  5. ArrayList can be iterated randomly as it works on the index
  6. ArrayList slows down when lot of insertion and deletion operations are happening because of lot of shifting of elements.

In this tutorial we will be learning the ArrayList Collection in friendly manner. Now lets create an ArrayList using following line of code –

Example #1 : Create Array List

package com.c4learn.set;
import java.util.ArrayList;

public class ArrayListExamples {

  public static void main(String[] args) {

    ArrayList<String> arrList1 = new ArrayList<String>();
    arrList1.add("ABC");
    arrList1.add("DEF");
    arrList1.add("GHI");
    
    //Display Array List
    System.out.println(arrList1);
  }
}

Output :

[ABC, DEF, GHI]

Now in the above example, we have created an array list. In order to print the arraylist we can just use the name of arraylist as a parameter to println method –

System.out.println(arrList1);

Example #2 : Using Iteration to Print ArrayList

Now in the above program, we have learnt to create an arraylist. Now we need to access each element of ArrayList and need to print each element seperatly.

package com.c4learn.set;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExamples {

  public static void main(String[] args) {

    ArrayList<String> arrList1 = new ArrayList<String>();
    arrList1.add("ABC");
    arrList1.add("DEF");
    arrList1.add("GHI");
    
    Iterator<String> itr = arrList1.iterator();

    while (itr.hasNext()) {
      String str = (String) itr.next();
      System.out.println(str);
    }
  }
}

Output :

ABC
DEF
GHI

We need to import iterator class using the below statement –

import java.util.Iterator;

Now we create an object of iterator class which will be used to iterator over a collection. While will returns true if the iteration has more elements or next element.

while (itr.hasNext()) {
	
}

Following line will be used to get the next element from the ArrayList

String str = (String) itr.next();