Author Topic: Explanation of Arraylist in java with example  (Read 4236 times)

Musfiqur Rahman

  • Newbie
  • *
  • Posts: 45
    • View Profile
    • Musfiqur Rahman
Explanation of Arraylist in java with example
« on: March 23, 2023, 01:42:15 PM »
ArrayList is a class in Java that provides a resizable array implementation of the List interface. It allows dynamic resizing of the array as elements are added or removed from the list. ArrayLists are part of the Java Collections Framework and are widely used in Java programming.

Here's an example of how to use ArrayList in Java:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        // create a new ArrayList
        ArrayList<String> list = new ArrayList<>();

        // add elements to the ArrayList
        list.add("apple");
        list.add("banana");
        list.add("orange");

        // get the size of the ArrayList
        int size = list.size();
        System.out.println("Size of ArrayList: " + size);

        // access elements in the ArrayList
        String firstElement = list.get(0);
        System.out.println("First element of ArrayList: " + firstElement);

        // remove an element from the ArrayList
        list.remove(1);
        System.out.println("Updated ArrayList: " + list);
    }
}

In this example, we create a new ArrayList of type String, add some elements to it, get the size of the ArrayList, access an element in the ArrayList, and remove an element from the ArrayList. Here's the output of the program:

Size of ArrayList: 3
First element of ArrayList: apple
Updated ArrayList: [apple, orange]

The ArrayList class provides many other useful methods for working with lists, such as add, addAll, remove, indexOf, contains, clear, and more. You can also create ArrayLists of other types, such as Integer, Double, or custom classes. Overall, ArrayLists provide a flexible and powerful way to manage collections of elements in Java.