Java 数据结构

Java 中常见数据结构的对应实现与选择依据。

Beginner
Key Points数组随机访问快、插入删除慢;链表相反;栈用 Deque、队列用 Queue;查找多用 HashMap。

常见数据结构与 Java 实现

Java ships the common structures in its collections framework, so you rarely implement them. Choose by operation mix: read-heavy or write-heavy, ordered or not, duplicates allowed or not.

StructureJava typeBest at
Dynamic arrayArrayListRandom access O(1)
Linked listLinkedListInsert/remove at ends
StackArrayDequeLIFO push/pop
QueueArrayDeque / LinkedListFIFO offer/poll
Hash tableHashMapKey lookup O(1)
Sorted mapTreeMapOrdered keys O(log n)
SetHashSet / TreeSetDeduplication

栈与队列的用法

Avoid the legacy Stack class; ArrayDeque serves as both stack and queue — push/pop for LIFO and offer/poll for FIFO.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class StackQueue {
    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        System.out.println(stack.pop());
        System.out.println(stack);

        Deque<Integer> queue = new ArrayDeque<>();
        queue.offer(1);
        queue.offer(2);
        System.out.println(queue.poll());
        System.out.println(queue);
    }
}
Output
2
[1]
1
[2]

复杂度速查

Decide the dominant operation first. ArrayList reads by index in O(1) but inserts mid-list in O(n); LinkedList is the reverse; HashMap averages O(1) but is unordered; TreeMap is O(log n) with sorted keys.

OperationArrayListLinkedListHashMap
get(i)O(1)O(n)—
add(end)O(1)*O(1)O(1)*
add(middle)O(n)O(1)—
remove(middle)O(n)O(1)O(1)*
containsO(n)O(n)O(1)

Friends & Partners