Java - ArrayList

In Java, an ArrayList is a dynamic data structure that allows you to store a collection of objects of the same type. Unlike traditional arrays, ArrayLists can grow or shrink in size at runtime, making them a more flexible option for managing collections of data.

To use ArrayList in Java, you need to import the java.util package which contains the ArrayList class.

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        // create an ArrayList to store integers
        ArrayList<Integer> numbers = new ArrayList<Integer>();

        // add elements to the ArrayList
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // access an element by index
        int firstElement = numbers.get(0);
        System.out.println(firstElement); // Output: 1

        // modify an element by index
        numbers.set(1, 4);
        System.out.println(numbers); // Output: [1, 4, 3]

        // remove an element by index
        numbers.remove(2);
        System.out.println(numbers); // Output: [1, 4]

        // get the size of the ArrayList
        int size = numbers.size();
        System.out.println(size); // Output: 2
    }
}

In this example, we first declare an ArrayList named numbers to store integers. We then add three elements to the ArrayList using the add() method.

We access the first element of the ArrayList using the get() method and store it in a variable named firstElement.

We modify the second element of the ArrayList using the set() method and remove the third element using the remove() method.

Adding elements to an ArrayList:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

Removing elements from an ArrayList:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
colors.remove("Green");

Accessing elements in an ArrayList:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
String firstColor = colors.get(0);

Iterating over an ArrayList:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
for (String color : colors) {
    System.out.println(color);
}

Sorting an ArrayList:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
Collections.sort(colors);

Checking if an ArrayList contains an element:

ArrayList<String> colors = new ArrayList<String>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");

if (colors.contains("Green")) {
    System.out.println("The list contains the color Green.");
} else {
    System.out.println("The list does not contain the color Green.");
}