Array List
ArrayList in Java
The ArrayList class in Java is a resizable array implementation of the List interface. It provides dynamic arrays that can grow or shrink in size as needed. ArrayLists are part of the Java Collections Framework and offer various methods for manipulating the elements stored in them.
Declaration and Initialization
To use an ArrayList in Java, you need to import the java.util.ArrayList
package. Here's an example of declaring and initializing an ArrayList:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
// Adding elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Accessing elements
System.out.println("Access Element = "+fruits.get(0)); // Output: Apple
// Modifying elements
fruits.set(1, "Mango");
// Removing elements
fruits.remove(2);
// Iterating over elements
for (String fruit : fruits) {
System.out.println("Iterating Elements = "+fruit);
}
}
}
Common ArrayList Operations
Here are some commonly used operations with ArrayLists:
add(element)
: Adds an element to the end of the ArrayList.get(index)
: Retrieves the element at the specified index.set(index, element)
: Replaces the element at the specified index with a new element.remove(index)
: Removes the element at the specified index.size()
: Returns the number of elements in the ArrayList.isEmpty()
: Checks if the ArrayList is empty.clear()
: Removes all elements from the ArrayList.
These are just a few examples of what you can do with ArrayLists in Java. They offer many more methods and can store objects of any type. ArrayLists provide a flexible way to work with collections of elements that can change in size.