An ArrayList
in Java is a resizable array implementation of the List
interface. It allows dynamic memory allocation, where elements can be added or removed as needed.
ArrayList
can dynamically resize itself, providing flexibility.Creating an ArrayList
is straightforward. Here’s the basic syntax:
ArrayList<Type> list = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
You can add elements using the add()
method:
names.add("Alice");
names.add("Bob");
You can also add elements at specific positions:
names.add(1, "Charlie");
Use the get()
method to access elements:
String firstElement = names.get(0);
Iterating with a for loop:
for (String name : names) {
System.out.println(name);
}