0% completed
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.
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.
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);
ArrayList<Type>
declares an ArrayList that stores objects of the specified Type
.add()
method inserts elements into the list.get(index)
method allows access to elements at a given position.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.
Example Explanation:
ArrayList<String>
named fruits
is created to store strings.add()
method is used to insert "Apple", "Banana", "Cherry", and "Date" into the list.get(0)
method retrieves the first element ("Apple"), and get(2)
retrieves the third element ("Cherry").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.
.....
.....
.....