Master Java ArrayList Methods: A Complete Guide with Examples & Real Use Cases
Source: Dev.to
What Actually is an ArrayList?
Under the hood, an ArrayList still uses an array, but it handles all the resizing logic for you. When it runs out of space, it creates a bigger array and copies everything over. The result is a dynamic array that gives you fast index‑based access plus the flexibility of a list.
Why Should You Care?
- You don’t know how many items you’ll have upfront.
- You need to frequently add/remove items.
- You still want fast random access (e.g., grabbing the item at position 5).
- You don’t need the ultra‑specific features of other collections (e.g.,
LinkedListfor constant‑time insertions at ends, orHashSetfor uniqueness).
The Essential ArrayList Methods, Decoded with Real Code
The Basics: Adding and Accessing Stuff
add(E element) & add(int index, E element)
ArrayList socialApps = new ArrayList<>();
socialApps.add("Instagram"); // Adds to the end
socialApps.add("Twitter");
socialApps.add(1, "TikTok"); // Inserts at index 1
// Order now: ["Instagram", "TikTok", "Twitter"]
Real‑world use: building a dynamic menu list in an Android app based on user permissions.
get(int index)
String currentFav = socialApps.get(0); // "Instagram"
Pro tip: always check bounds or use safe methods in production to avoid IndexOutOfBoundsException.
set(int index, E element)
socialApps.set(2, "Snapchat"); // Replaces element at index 2
Knowing What’s Inside: Checking and Finding
- size() – replacement for
array.length.socialApps.size()returns3. - isEmpty() – returns
trueif the list contains no elements. - contains(Object o) & indexOf(Object o)
boolean hasTikTok = socialApps.contains("TikTok"); // true
int pos = socialApps.indexOf("Instagram"); // 0
Real‑world use: validating if a username already exists before sign‑up.
The Cleanup Crew: Removing Elements
remove(int index) & remove(Object o)
socialApps.remove(1); // Removes "TikTok" by index
socialApps.remove("X"); // Attempts to remove "X" by object
Watch out:
remove(1)removes by index, whileremove(Integer.valueOf(1))removes the number1from anArrayList.
clear() – removes all elements, leaving an empty list.
socialApps.clear(); // List is now empty
Leveling Up: Bulk Operations and Iteration
addAll(Collection c) – merge lists like a pro.
ArrayList newApps = new ArrayList<>(Arrays.asList("Threads", "Bluesky"));
socialApps.addAll(newApps);
subList(int fromIndex, int toIndex) – obtains a view (not a copy) of a portion of the list, useful for pagination.
Iterating Over an ArrayList
// For‑each (simple)
for (String app : socialApps) {
System.out.println(app);
}
// Iterator (safe for removal during loop)
Iterator it = socialApps.iterator();
while (it.hasNext()) {
if (it.next().contains("a")) {
it.remove(); // Safely remove while iterating
}
}
// Java 8+ forEach with lambda (clean)
socialApps.forEach(app -> System.out.println(app));
Initial Capacity – if you know you’ll store, say, 10 000 items, use new ArrayList<>(10000) to avoid repeated resizing.
Performance Notes
get(index)andset(index, element)are O(1) – constant‑time.add(element)is O(1) amortized (usually fast; occasional resizing incurs a copy).add(index, element)andremove(index)are O(n) – slower for large lists when operating near the front because elements must shift.- Synchronization:
ArrayListis not thread‑safe. UseCollections.synchronizedList(new ArrayList<>())or a concurrent collection if multiple threads access it. - Copying:
new ArrayList<>(oldList)creates a shallow copy; the objects inside are shared between lists.
Real‑World Use Case: E‑Commerce Shopping Cart
ArrayList cart = new ArrayList<>();
// User adds items
cart.add(new CartItem("Java Programming Book", 1, 29.99));
cart.add(new CartItem("USB‑C Cable", 2, 15.99));
// Update quantity of first item
CartItem firstItem = cart.get(0);
firstItem.setQuantity(2);
// User removes an item
cart.removeIf(item -> item.getName().contains("Cable")); // Remove all cables
// Checkout – calculate total
double total = 0;
for (CartItem item : cart) {
total += item.getPrice() * item.getQuantity();
}
// Clear cart after order
cart.clear();
FAQ
- Q: Array vs. ArrayList in 2024?
- Q: How do I sort an ArrayList?
- Q: Can I store primitives in an ArrayList?
- Q: Is ArrayList memory efficient?
Wrapping It Up
Collections are a massive part of professional Java development. Mastering ArrayList methods gives you a solid foundation for building production‑ready applications. Keep experimenting, write code, and let those dynamic lists work for you!