Java: List and ArrayList

ArrayList is the most commonly used collection. This lesson covers detailed List usage.

1. ArrayList

ArrayList is a dynamic array based on array implementation.

(1) 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

(2) Creating ArrayList

TEXT 📖 Display only
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);

2. Basic Operations

(1) 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]

(2) Getting Elements

TEXT 📖 Display only
List<String> list = new ArrayList<>();
list.add("Alice");
list.add("Bob");

String first = list.get(0);  // Alice
int size = list.size();       // 2

(3) 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]

(4) Removing Elements

TEXT 📖 Display only
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]

(5) 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

3. Traversal Methods

(1) Method 1: for Loop

TEXT 📖 Display only
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));
}

(2) Method 2: for-each

JAVA
for (String name : list) {
    System.out.println(name);
}

(3) Method 3: Iterator

TEXT 📖 Display only
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

(4) Method 4: Lambda

JAVA
list.forEach(name -> System.out.println(name));
list.forEach(System.out::println);

4. Sorting

(1) Using Collections.sort()

TEXT 📖 Display only
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]

(2) 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]

5. 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

TEXT 📖 Display only
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]

6. LinkedList

LinkedList is a List implementation based on doubly-linked list.

(1) 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)

(2) 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();

(3) 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);
    }
}
▶ Try it Yourself

7. ❓ 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.

❓ FAQ

Q Can I resize an array?
A No. Arrays have fixed size. Use ArrayList for dynamic sizing.
Q What happens if I access an invalid index?
A An ArrayIndexOutOfBoundsException is thrown at runtime.
Q How to sort an array?
A Use Arrays.sort() for primitives or Arrays.sort() with a Comparator for objects.

📖 Summary

📝 Exercises

  1. Deduplication: Remove duplicate elements from an ArrayList
  2. Merge: Merge two sorted Lists into one sorted List
  3. Count: Count occurrences of each element in a List

8. Next Lesson

In the next lesson, we'll learn about Set and HashSet — understanding Set's deduplication mechanism.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏