Collection Framework Overview

Collections are core tools for storing and manipulating data. This lesson covers the overall structure of Java's Collection Framework.

Why Collections are Needed

Arrays have fixed size limitations; collections can grow dynamically.

Arrays vs Collections

Feature Array Collection
Size Fixed Dynamic
Type Primitives/Objects Objects only
Methods None Rich methods
Generics Not supported Supported

Collection Framework Architecture

TEXT
Collection (interface)
├── List (interface) — Ordered, allows duplicates
│   ├── ArrayList (implementation)
│   ├── LinkedList (implementation)
│   └── Vector (implementation)
├── Set (interface) — Unordered, no duplicates
│   ├── HashSet (implementation)
│   ├── TreeSet (implementation)
│   └── LinkedHashSet (implementation)
└── Queue (interface) — Queue
    ├── LinkedList (implementation)
    └── PriorityQueue (implementation)

Map (interface) — Key-value pairs
├── HashMap (implementation)
├── TreeMap (implementation)
├── LinkedHashMap (implementation)
└── Hashtable (implementation)

Collection Interface

Collection is the parent interface for all single-value collections.

Common Methods

Method Description Return Type
add(E e) Add element boolean
remove(Object o) Remove element boolean
contains(Object o) Contains element boolean
isEmpty() Is empty boolean
size() Element count int
clear() Clear all void
toArray() Convert to array Object[]

Example: Basic Collection Operations

JAVA
import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        
        // Add elements
        collection.add("Alice");
        collection.add("Bob");
        collection.add("Charlie");
        System.out.println("Collection: " + collection);  // [Alice, Bob, Charlie]
        
        // Check
        System.out.println("Contains Alice: " + collection.contains("Alice"));  // true
        System.out.println("Size: " + collection.size());  // 3
        System.out.println("Is empty: " + collection.isEmpty());  // false
        
        // Remove
        collection.remove("Bob");
        System.out.println("After remove: " + collection);  // [Alice, Charlie]
        
        // Convert to array
        Object[] array = collection.toArray();
        for (Object obj : array) {
            System.out.println(obj);
        }
        
        // Clear
        collection.clear();
        System.out.println("After clear, size: " + collection.size());  // 0
    }
}
▶ Try it Yourself

Iterable and Iterator

Iterable Interface

Classes that implement Iterable can be traversed with for-each.

Iterator Interface

Iterator is used to traverse collections.

Method Description
hasNext() Has next element
next() Get next element
remove() Remove current element

Example: Using Iterator

JAVA
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        
        // Method 1: for-each
        for (String name : names) {
            System.out.println(name);
        }
        
        // Method 2: Iterator
        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            String name = it.next();
            System.out.println(name);
        }
        
        // Method 3: Remove with Iterator
        Iterator<String> it2 = names.iterator();
        while (it2.hasNext()) {
            String name = it2.next();
            if (name.startsWith("B")) {
                it2.remove();  // Safe removal
            }
        }
        System.out.println("After remove: " + names);  // [Alice, Charlie]
    }
}
▶ Try it Yourself
⚠️ Note: When removing elements during traversal, use Iterator's remove method, not the collection's remove method, otherwise ConcurrentModificationException will be thrown.

List Interface

Ordered collection, allows duplicates.

Characteristics

Feature Description
Ordered Elements in insertion order
Allows duplicates Can have same elements
Index access Access elements by index

Common Methods

Method Description
get(int index) Get element at index
set(int index, E e) Set element at index
add(int index, E e) Insert at position
remove(int index) Remove element at index
indexOf(Object o) Find element index
subList(int from, int to) Get sub-list

Set Interface

Unordered collection, no duplicates.

Characteristics

Feature Description
Unordered No fixed order
No duplicates Automatic deduplication
No index Cannot access by index

Map Interface

Key-value pair collection, keys cannot be duplicated.

Characteristics

Feature Description
Key-value pairs Each element has key and value
Unique keys Keys unique, values can repeat
Unordered HashMap is unordered

Common Methods

Method Description
put(K k, V v) Add key-value pair
get(K k) Get value by key
remove(K k) Remove key-value pair
containsKey(K k) Contains key
keySet() All keys
values() All values
entrySet() All key-value pairs

Collection Selection Guide

Need Choice
Ordered, allows duplicates ArrayList
Unordered, no duplicates HashSet
Ordered, no duplicates LinkedHashSet
Sorted, no duplicates TreeSet
Key-value pairs HashMap
Sorted key-value pairs TreeMap

❓ Frequently Asked Questions

Q How to choose between ArrayList and LinkedList?
A Use ArrayList for frequent queries. Use LinkedList for frequent additions/deletions. Generally use ArrayList.
Q How does HashSet deduplication work?
A First compares hashCode, then compares equals. Both must match to be considered duplicate.
Q What's the difference between HashMap and Hashtable?
A HashMap is not thread-safe but faster. Hashtable is thread-safe but slower. HashMap is recommended.

📖 Summary

📝 Exercises

  1. Collection operations: Create an ArrayList, add 10 elements, traverse and remove even numbers
  2. Deduplication: Remove duplicate elements from an array (use HashSet)
  3. Map practice: Count occurrences of each character in a string

Next Lesson

In the next lesson, we'll learn about List and ArrayList — detailed usage of List.

100%

🙏 帮我们做得更好

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

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