HIDE NAV

ArrayList Basics

The below command line program demonstrates basic use of ArrayLists which are similar to arrays but dynamically resizeable.he basics of array declaration and access.

Main.java


package ceccs;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        //Conventional Array - Fixed size, cannot be resized
        System.out.println("Array:");
        String[] strArray;
        strArray = new String[3];
        strArray[0] = "1st string";
        strArray[1] = "2nd string";
        strArray[2] = "3rd string";
        for(int i = 0; i < strArray.length; i++){
            System.out.println(strArray[i]);
        }

        //ArrayList - Dynamically Resizable
        System.out.println("\n\nArray List:");
        ArrayList<String> strArrayList;
        strArrayList = new ArrayList();
        strArrayList.add("1st String");
        strArrayList.add("2nd String");
        strArrayList.add("3rd String");
        for (int i = 0; i < strArrayList.size(); i++){
            System.out.println(strArrayList.get(i));
        }
        // Adding and removing from an array list
        System.out.println("\nAdding and Removing:");
        strArrayList.remove(1);
        strArrayList.add("4th string");
        for (int i = 0; i < strArrayList.size(); i++){
            System.out.println(strArrayList.get(i));
        }

    }
}