Java Intermediate

0% completed

Previous
Next
Basic overview of ArrayList Class

The ArrayList class is a dynamic array implementation of the List interface in Java. It is one of the most commonly used collection classes because it provides flexible storage that can grow or shrink as needed.

Image

An ArrayList stores elements in an ordered sequence and allows duplicate entries. Since it implements the List interface, it supports all the standard list operations such as adding, removing, updating, and accessing elements by index.

ArrayList is preferred when fast random access is required. Although inserting or deleting elements in the middle of the list might be slower compared to a linked list, its dynamic resizing and ease of use make it a popular choice in many applications.

Syntax and Accessing Elements

Below is the basic syntax for creating an ArrayList and accessing its elements:

// Declaring and creating an ArrayList ArrayList<Type> list = new ArrayList<Type>(); // Adding an element to the ArrayList list.add(element); // Accessing an element by index Type value = list.get(index);
  • Explanation:
    • ArrayList<Type> declares an ArrayList that stores objects of the specified Type.
    • The ArrayList class implements the List interface, which means it provides all standard list operations.
    • The add() method inserts elements into the list.
    • The get(index) method allows access to elements at a given position.

Example: Creating and Accessing Elements in an ArrayList

In this example, we create an ArrayList of strings to store names of fruits. We add several fruit names to the list and then demonstrate how to access elements by index as well as display the entire list.

Java
Java

. . . .

Example Explanation:

  • ArrayList Creation:
    • An ArrayList<String> named fruits is created to store strings.
  • Adding Elements:
    • The add() method is used to insert "Apple", "Banana", "Cherry", and "Date" into the list.
  • Accessing Elements:
    • The get(0) method retrieves the first element ("Apple"), and get(2) retrieves the third element ("Cherry").
  • Displaying the List:
    • The entire list is printed to show all elements in the order they were added.

The ArrayList class in Java provides a dynamic array that implements the List interface, allowing you to use all standard list operations. Understanding these basics is crucial as you move on to more advanced operations with ArrayList, such as insertion at specific positions, removal of elements, and sorting.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next