What is ArrayList In Java

ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable

In Java, an ArrayList is a part of the Java Collections Framework and is implemented in the java.util package. It is a dynamic array that can grow or shrink in size at runtime. ArrayList provides a resizable array-like structure that allows for the insertion and deletion of elements.

Key features of ArrayList include:

  1. Dynamic Sizing: Unlike arrays in Java, ArrayLists can dynamically resize themselves, automatically increasing or decreasing in size as elements are added or removed.
  2. Random Access: Elements in an ArrayList can be accessed using an index, just like in arrays. This allows for efficient random access to elements.
  3. Generic: ArrayLists in Java are generic, meaning they can hold elements of a specific type. You can specify the type of elements an ArrayList will hold when creating an instance, ensuring type safety.
  4. Methods: ArrayList provides various methods for adding, removing, and accessing elements. Some common methods include add(), remove(), get(), size(), etc.

Here is a simple example of how to create and use an ArrayList in Java:

java

import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();

// Adding elements to the ArrayList
fruits.add(“Apple”);
fruits.add(“Banana”);
fruits.add(“Orange”);

// Accessing elements using index
System.out.println(“First fruit: “ + fruits.get(0));

// Iterating through the ArrayList
System.out.println(“Fruits in the list:”);
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

This example demonstrates the basic usage of an ArrayList with Strings, but you can use ArrayLists to store objects of any type.