- Master ArrayList creation and operations
- Learn add, remove, get, set methods
- Understand ArrayList iteration
Working with Lists (ArrayList)
ArrayList is the most commonly used collection in Java. It's a resizable array implementation of the List interface, offering dynamic sizing, rich functionality, and excellent performance for most use cases.
Creating an ArrayList
// Empty ArrayList
ArrayList<String> names = new ArrayList<>();
// ArrayList with initial capacity
ArrayList<Integer> numbers = new ArrayList<>(100);
// ArrayList from another collection
List<String> list1 = Arrays.asList("A", "B", "C");
ArrayList<String> list2 = new ArrayList<>(list1);
Common ArrayList Operations
Adding Elements
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple"); // Add to end
fruits.add("Banana");
fruits.add(1, "Orange"); // Add at specific index
Accessing Elements
String first = fruits.get(0); // Get element at index
int size = fruits.size(); // Get number of elements
boolean empty = fruits.isEmpty(); // Check if empty
Modifying Elements
fruits.set(1, "Grape"); // Replace element at index
Removing Elements
fruits.remove(0); // Remove by index
fruits.remove("Apple"); // Remove by object
fruits.clear(); // Remove all elements
Searching
boolean contains = fruits.contains("Apple");
int index = fruits.indexOf("Banana"); // -1 if not found
Iterating Through ArrayList
Using For-Each Loop
for (String fruit : fruits) {
System.out.println(fruit);
}
Using Traditional For Loop
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
Using Iterator
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
ArrayList Best Practices
Use interfaces for variable types:
List<String> list = new ArrayList<>(); // PreferredInitialize with capacity if size is known:
List<String> list = new ArrayList<>(1000);Use generics for type safety:
ArrayList<String> list = new ArrayList<>(); // Type-safe
ArrayList gives you dynamic resizing, fast random access (O(1)), and efficient iteration. Perfect for most list operations where you need indexed access and don't frequently insert or remove from the middle.
