ArrayList

An ArrayList in Java is a resizable array that can store a collection of elements. It allows you to add, remove, and access elements, and automatically adjusts its size as needed when elements are added or removed. Unlike regular arrays, you don’t need to specify the size in advance.

It is a class in Java that implements the List interface and provides a flexible way to store and manage a collection of elements. It is stored in heap memory and allows random access to elements using an index.

Key Features of ArrayList

  • Automatic Resizing: Expands as new elements are added and contracts when elements are removed.
  • Index-Based Access: Elements can be retrieved or modified using their index position.
  • Built in methods: Includes built-in methods such as add(), remove(), get(), and size() for efficient list management.

Common Methods

Below is a brief overview of some common ArrayList methods in Java:

  • add(): Adds a new element to the list.
  • remove(): Deletes an element from the list.
  • get(): Retrieves an element at a specified index.
  • size(): Returns the total count of elements in the list.

Example of ArrayList

1. Create an ArrayList of String

ArrayList<String> list = new ArrayList<>();

2. Add an element to the ArrayList

list.add("Apple");

3. Remove an element from the ArrayList

list.remove(0); // Removes "Banana" (index 0)

4. Get the size of the ArrayList

int size = list.size(); // Returns the total count of elements in the list

Leave a Comment