Lesson 2 of 10
List - ArrayList & LinkedList
List is the most commonly used collection - an ordered sequence that allows duplicates and index-based access. ArrayList is backed by a resizable array; LinkedList is a doubly-linked list. Understanding their internals explains their performance characteristics.
ArrayList - Complete API
ArrayList - Complete API
import java.util.*;
public class ListDemo {
public static void main(String[] args) {
List<String> books = new ArrayList<>();
// Add
books.add("Clean Code");
books.add("Effective Java");
books.add("Java Concurrency");
books.add(1, "DDIA"); // insert at index 1
books.addAll(List.of("Refactoring", "Design Patterns")); // add multiple
System.out.println(books); // [Clean Code, DDIA, Effective Java, Java Concurrency, Refactoring, Design Patterns]
System.out.println("Size: " + books.size()); // 6
System.out.println("Get(0): " + books.get(0)); // "Clean Code"
System.out.println("Contains: " + books.contains("DDIA")); // true
System.out.println("Index of: " + books.indexOf("DDIA")); // 1
// Update
books.set(0, "Clean Architecture");
System.out.println(books.get(0)); // Clean Architecture
// Remove
books.remove("DDIA"); // remove by value
books.remove(0); // remove by index - returns removed element
// Sublist (view - not a copy!)
List<String> sub = books.subList(0, 2); // [0, 2) - indices 0 and 1
System.out.println(sub);
// Sort
Collections.sort(books); // natural order (alphabetical)
books.sort(Comparator.comparingInt(String::length)); // by length
books.sort(Comparator.reverseOrder()); // reverse alphabetical
// Iteration
for (String book : books) System.out.println(book); // for-each
books.forEach(System.out::println); // method reference
for (int i = 0; i < books.size(); i++) { // indexed (when index needed)
System.out.printf("%d: %s%n", i + 1, books.get(i));
}
// Convert array ↔ list
String[] arr = books.toArray(String[]::new); // Java 11+
List<String> fromArr = new ArrayList<>(Arrays.asList(arr));
// Clear & empty check
books.clear();
System.out.println(books.isEmpty()); // true
}
}Diagram
Loading diagram…
Visual architecture and concepts for List - ArrayList & LinkedList
Quick Quiz
Finished this lesson?
0 of 10 in Module 5