ArrayList Class in JAVA JAVA by Ravinder Nath Rajotiya - April 18, 20210 Share on Facebook Share Send email Mail Print Print ArrayList class in JAVA We have already seen that arrays are of a fixed length and after they are created, they cannot grow or shrink. This meant the the programmer must know in advance about the size requirement of an array. ArrayList like arrays also allow object storage, but unlike array, the arrayList are created with an initial size, the arrayList collection is automatically enlarged when object are added and it automatically get shrunk when objects are removed from the arrayList. There is a class ArrayList to which is in java.util.* package. You always work with ArrayList Object which you pass it to it as: ArrayList<Integer> // Use class names as Integer, remember you cannot use primitive data type as int ArrayList<String> names = new ArrayList<>(); Syntax: Declare ArrayList<> ArrayList<String> names = new ArrayList<>(); Adding items to ArrayList<> The following statements will add items in sequence to ArrayList names.add(“Abhay”); //this is same as name at position ‘0’ names.add(“Balwan”); //position 1 names.add(“Chetan”); // will go to position 2 names.add(“Dayanand”); //position 3 names.add(“Exta”); //position 4 Adding item at specific position Inserting values at a specific position, but move any item over their at that index down the list names.add(3,“Chotu“); //This will insert object Chotu at position 3 and shift exisiting value at that index down, So, Dayanand will take position at index 4 and Ekta will go to position 5 in ArrayList<> To set a value to different one To set a value at a position to different names.set(3,“Vikas“); // This will replace Chotu with Vikas at position 3. Chotu will not now existing Removing an item from the List names.remove(index 2); // This will totally remove the position 2 values and shrink the arrayList<> upwards Finding the size of ArrayList<> Size of ArraList<> is given by object.size() will return exact values in the ArrayList<> Print the values in the ArrayList<> System.out.println(names.get(i) Example: package com.example; import java.util.ArrayList; public class arrays { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add(“Abhay”); //this is same as name at position ‘0’ names.add(“Balwan”); //position 1 names.add(“Chetan”); // will go to position 2 names.add(“Dayanand”); //position 3 names.add(4, “Ekta”); names.set(2, “Chota Chetan”); for (int i = 0; i < names.size(); i++) { System.out.println(names.get(i)); } } } Run the program and you get the following output Abhay Balwan Chota Chetan Dayanand Ekta Process finished with exit code 0 Share on Facebook Share Send email Mail Print Print