ArrayList example

In this example we are going to see the java ArrayList in action. List is the interface and ArrayList is the implementation of the List interface.

Here, we are going to create a list which will take Integer types and then we are going to iterate them in a loop and print out the result.

package com.amzi.examples;

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {

    public static void main(String[] args) {

        // invoke and create the list of 5 Integer objects
        // declaring generics type as Integer so only Integer value can fit in
        // instead of Integer type we can also add String or other Object type
        List<Integer> list = new ArrayList<Integer>(5);
        // calling add method to add the element into the list
        list.add(15);
        list.add(20);
        list.add(25);
        list.add(15);
        list.add(20);
        list.add(15);// duplicate values can be added
        list.add(null);// null also can be added.

        // loop through the list elements
        for (Integer index : list) {
            System.out.println("First List elements: " + index);
        }
        System.out.println("========================");

        // at second position of the existing list, adding new Integer value
        // list index starts from 0
        list.add(2, 22);

        // loop through the list after adding the new element
        for (Integer index : list) {
            System.out.println("Second list elements: " + index);
        }
    }
}


Output:

First List elements: 15
First List elements: 20
First List elements: 25
First List elements: 15
First List elements: 20
First List elements: 15
First List elements: null
========================
Second list elements: 15
Second list elements: 20
Second list elements: 22
Second list elements: 25
Second list elements: 15
Second list elements: 20
Second list elements: 15
Second list elements: null

No comments:

Post a Comment