Java 中常见的数据结构类型包括以下几种:
- 数组(Array):一组有序的数据元素,可以通过下标来访问元素。例如:
int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers[0]); // 输出 1
- 链表(Linked List):一组通过指针相连的节点,每个节点包含一个数据元素和指向下一个节点的指针。例如:
class Node {
int data; Node next; public Node(int data) {
this.data = data; this.next = null;
} }
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
}
- 栈(Stack):一种先进后出(Last-In-First-Out,LIFO)的数据结构,只允许在栈顶进行插入和删除操作。例如:
Stack<Integer> stack = new Stack<>();
stack.push(1); stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // 输出 3
- 队列(Queue):一种先进先出(First-In-First-Out,FIFO)的数据结构,允许在队尾进行插入操作,在队头进行删除操作。例如:
Queue<Integer> queue = new LinkedList<>();
queue.offer(1); queue.offer(2);
queue.offer(3);
System.out.println(queue.poll()); // 输出 1
- 树(Tree):一种由节点和边组成的层次结构,每个节点可以有多个子节点。例如:
class TreeNode {
int val; TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
} }
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
除了我之前提到的数据结构,Java 中还有以下常见的数据结构:
- 哈希表(Hash Table):一种通过哈希函数将键映射到值的数据结构,可以快速地进行插入、查找和删除操作。例如:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
System.out.println(map.get("apple")); // 输出 1
- 堆(Heap):一种可以快速找到最大值或最小值的数据结构,通常用于实现优先队列。例如:
PriorityQueue<Integer> maxHeap = new PriorityQueue<(Collections.reverseOrder());
maxHeap.offer(1);
maxHeap.offer(3);
maxHeap.offer(2);
System.out.println(maxHeap.poll()); // 输出 3
- 图(Graph):一种由节点和边组成的非线性数据结构,用于表示各种关系。例如:
class Graph {
int V;
List<Integer>[] adj;
public Graph(int V) {
this.V = V;
adj = new List[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
} }
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
} }
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
- 字符串(String):一种由字符组成的有序序列,通常用于存储文本信息。例如:
String str = "Hello, world!";
System.out.println(str.charAt(0)); // 输出 H