List and ArrayList
ArrayList is the most commonly used collection. This lesson covers detailed List usage.
ArrayList
ArrayList is a dynamic array based on array implementation.
Characteristics
| Feature | Description |
|---|---|
| Ordered | Elements in insertion order |
| Allows duplicates | Can have same elements |
| Index access | Access elements by index |
| Dynamic growth | Automatic capacity expansion |
Creating ArrayList
JAVA
import java.util.ArrayList;
import java.util.List;
// Method 1: Default capacity
List<String> list1 = new ArrayList<>();
// Method 2: Specified capacity
List<String> list2 = new ArrayList<>(100);
// Method 3: From another collection
List<String> list3 = new ArrayList<>(list1);
Basic Operations
Adding Elements
JAVA
List<String> list = new ArrayList<>();
list.add("Alice"); // Add to end
list.add("Bob");
list.add(0, "Charlie"); // Add at specific position
System.out.println(list); // [Charlie, Alice, Bob]
Getting Elements
JAVA
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
String first = list.get(0); // Alice
int size = list.size(); // 2
Modifying Elements
JAVA
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
list.set(0, "Charlie"); // Change first element to Charlie
System.out.println(list); // [Charlie, Bob]
Removing Elements
JAVA
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
list.add("Charlie");
list.remove(0); // Remove by index
list.remove("Bob"); // Remove by content
System.out.println(list); // [Charlie]
Finding Elements
JAVA
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
list.add("Charlie");
boolean has = list.contains("Bob"); // true
int index = list.indexOf("Charlie"); // 2
int lastIndex = list.lastIndexOf("Alice"); // 0
Traversal Methods
Method 1: for Loop
JAVA
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");
list.add("Charlie");
for (int i = 0; i < list.size(); i++) {
System.out.println(i + ": " + list.get(i));
}
Method 2: for-each
JAVA
for (String name : list) {
System.out.println(name);
}
Method 3: Iterator
JAVA
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Method 4: Lambda
JAVA
list.forEach(name -> System.out.println(name));
list.forEach(System.out::println);
Sorting
Using Collections.sort()
JAVA
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(4);
numbers.add(1);
numbers.add(5);
Collections.sort(numbers); // Ascending
System.out.println(numbers); // [1, 1, 3, 4, 5]
Collections.sort(numbers, Collections.reverseOrder()); // Descending
System.out.println(numbers); // [5, 4, 3, 1, 1]
Using Comparator
JAVA
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// Alphabetical order
names.sort((a, b) -> a.compareTo(b));
System.out.println(names); // [Alice, Bob, Charlie]
// By length
names.sort(Comparator.comparingInt(String::length));
System.out.println(names); // [Bob, Alice, Charlie]
Other Common Methods
| Method | Description |
|---|---|
addAll(Collection) |
Add all elements |
removeAll(Collection) |
Remove all matching elements |
retainAll(Collection) |
Keep intersection |
clear() |
Clear all |
isEmpty() |
Is empty |
toArray() |
Convert to array |
subList(int, int) |
Get sub-list |
Example: Batch Operations
JAVA
List<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
list1.add("C");
List<String> list2 = new ArrayList<>();
list2.add("B");
list2.add("C");
list2.add("D");
// Union
List<String> union = new ArrayList<>(list1);
union.addAll(list2);
System.out.println("Union: " + union); // [A, B, C, B, C, D]
// Intersection
List<String> intersection = new ArrayList<>(list1);
intersection.retainAll(list2);
System.out.println("Intersection: " + intersection); // [B, C]
// Difference
List<String> diff = new ArrayList<>(list1);
diff.removeAll(list2);
System.out.println("Difference: " + diff); // [A]
LinkedList
LinkedList is a List implementation based on doubly-linked list.
Characteristics
| Feature | ArrayList | LinkedList |
|---|---|---|
| Underlying structure | Array | Doubly-linked list |
| Random access | O(1) | O(n) |
| Insert at head | O(n) | O(1) |
| Insert at tail | O(1) | O(1) |
| Memory usage | Less | More (pointers) |
LinkedList Specific Methods
JAVA
LinkedList<String> linkedList = new LinkedList<>();
// Head/tail operations
linkedList.addFirst("A");
linkedList.addLast("B");
linkedList.addLast("C");
String first = linkedList.getFirst();
String last = linkedList.getLast();
linkedList.removeFirst();
linkedList.removeLast();
Selection Guide
| Scenario | Recommendation |
|---|---|
| Frequent random access | ArrayList |
| Frequent head insert/delete | LinkedList |
| General use | ArrayList |
Example: Student Grade Management
JAVA
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class StudentGrade {
private String name;
private int score;
public StudentGrade(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() { return name; }
public int getScore() { return score; }
@Override
public String toString() {
return name + ": " + score;
}
public static void main(String[] args) {
List<StudentGrade> students = new ArrayList<>();
students.add(new StudentGrade("Alice", 95));
students.add(new StudentGrade("Bob", 88));
students.add(new StudentGrade("Charlie", 92));
students.add(new StudentGrade("David", 85));
// Sort by score descending
students.sort((a, b) -> b.getScore() - a.getScore());
System.out.println("Sorted by score:");
students.forEach(System.out::println);
// Find highest score
StudentGrade top = students.stream()
.max(Comparator.comparingInt(StudentGrade::getScore))
.orElse(null);
System.out.println("Highest: " + top);
// Calculate average
double avg = students.stream()
.mapToInt(StudentGrade::getScore)
.average()
.orElse(0);
System.out.printf("Average: %.1f%n", avg);
}
}
❓ Frequently Asked Questions
Q What's the initial capacity of ArrayList?
A Default is 10. If you know the approximate size, specify it in the constructor to reduce resizing.
Q What's ArrayList's resizing mechanism?
A Each resize increases capacity by 1.5 times.
Q Can List store null?
A Both ArrayList and LinkedList can store null.
📖 Summary
- ArrayList is array-based, fast for queries, slow for insertions/deletions
- LinkedList is linked-list-based, fast for insertions/deletions, slow for queries
- Common operations: add/get/set/remove/contains/sort
- Traversal methods: for/for-each/Iterator/Lambda
📝 Exercises
- Deduplication: Remove duplicate elements from an ArrayList
- Merge: Merge two sorted Lists into one sorted List
- Count: Count occurrences of each element in a List
Next Lesson
In the next lesson, we'll learn about Set and HashSet — understanding Set's deduplication mechanism.



