Learn about ArrayList and how to maintain ordered collections of objects in Java.
ArrayLists are a flexible implementation of the List interface that use arrays internally to store elements. Unlike arrays, they don't require a fixed size and can grow dynamically.
You can add elements to an ArrayList using the add()
method in two ways:
// Adding to the end of the list ArrayList<String> coffeeOrders = new ArrayList<String>(); coffeeOrders.add("small coffee"); // Adding at a specific index coffeeOrders.add(5, "large latte");
When adding at a specific index, all elements at that index and beyond are shifted right, making this an O(n) operation in the worst case.
The remove()
method allows you to remove elements by index:
// Remove element at index 10 coffeeOrders.remove(10);
After removal, all elements beyond the removed index shift left to fill the gap, making this an O(n) operation.
You can iterate through all elements in an ArrayList to perform operations on each item:
// Using a standard for loop for (int i = 0; i < coffeeOrders.size(); i++) { System.out.println(coffeeOrders.get(i)); } // Using enhanced for loop (for-each) for (String order : coffeeOrders) { System.out.println(order); }
Understanding the performance of ArrayList operations is crucial: