Java操作蓝图:常用数据结构与方法

这是为了可以快速使用各种常用数据结构和方法的蓝图集合,通过给出一个空框架,提高效率。

最近刷题陷入了迷茫,往往不知道该用什么数据结构,所以我决定写一个蓝图,方便以后使用。

目录

  1. 数组(Array)
  2. 列表(List/ArrayList)
  3. 链表(LinkedList)
  4. 栈(Stack)
  5. 队列(Queue)
  6. 优先队列(PriorityQueue)
  7. 集合(Set/HashSet)
  8. 有序集合(TreeSet)
  9. 映射(Map/HashMap)
  10. 有序映射(TreeMap)
  11. 字符串操作(String)
  12. 工具类(Collections/Arrays)

接下来我对以上12个常用数据结构的用途做下简单的描述
数组:

  • 用途:固定大小的连续内存空间,存储相同类型元素
  • 解决问题:快速随机访问,内存紧凑
    列表:
  • 用途:动态数组,自动扩容
  • 解决问题:需要动态调整大小的数组
    链表:
  • 用途:双向链表实现,高效插入删除
  • 解决问题:频繁在列表中间进行插入/删除操作
    栈:
  • 用途:后进先出(LIFO)结构
  • 解决问题:需要后进先出逻辑的场景,如撤销操作、括号匹配
    队列:
  • 用途:先进先出(FIFO)结构
  • 解决问题:任务调度、广度优先搜索等
    优先队列:
  • 用途:元素按照优先级排序的队列
  • 解决问题:需要按照优先级处理元素的场景
    集合:
  • 用途:存储唯一元素的集合
  • 解决问题:去重、查找
    有序集合:
  • 用途:元素按照自然顺序或自定义顺序排序的集合
  • 解决问题:需要元素有序的场景
    映射:
  • 用途:键值对存储
  • 解决问题:根据键快速查找值
    有序映射:
  • 用途:键值对按照键的自然顺序或自定义顺序排序
  • 解决问题:需要键值对有序的场景
    字符串操作:
  • 用途:处理文本数据
  • 解决问题:字符串拼接、查找、替换
    工具类:
  • 用途:提供各种常用操作的静态方法
  • 解决问题:简化常见操作,如排序、查找、比较等

数组(Array)

用途:固定大小的连续内存空间,存储相同类型元素
解决问题:快速随机访问,内存紧凑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 声明与初始化
int[] arr = new int[10]; // 声明长度为10的整型数组
int[] arr2 = {1, 2, 3}; // 声明并初始化

// 常用操作
arr[0] = 5; // 赋值
int length = arr.length; // 获取长度(不是方法,是属性)

// 遍历数组
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

// 增强for循环
for (int num : arr) {
System.out.println(num);
}

// 多维数组
int[][] matrix = new int[3][3];
matrix[0][0] = 1;

列表(List/ArrayList)

用途:动态数组,自动扩容
解决问题:需要动态调整大小的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 创建ArrayList
List<String> list = new ArrayList<>(); // 推荐使用接口类型声明

// 添加元素
list.add("Apple");
list.add(0, "Banana"); // 在指定位置插入

// 获取元素
String fruit = list.get(0);

// 修改元素
list.set(0, "Orange");

// 删除元素
list.remove(0); // 按索引删除
list.remove("Orange"); // 按元素删除

// 大小检查
int size = list.size();
boolean isEmpty = list.isEmpty();

// 包含检查
boolean contains = list.contains("Apple");

// 遍历
for (String item : list) {
System.out.println(item);
}

// 使用迭代器
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// 转换为数组
String[] array = list.toArray(new String[0]);

链表(LinkedList)

用途:双向链表实现,高效插入删除
解决问题:频繁在列表中间进行插入/删除操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 创建LinkedList
List<String> linkedList = new LinkedList<>();

// 添加元素 (与ArrayList类似)
linkedList.add("A");
linkedList.addFirst("B"); // 特有方法
linkedList.addLast("C"); // 特有方法

// 获取元素
String first = linkedList.getFirst();
String last = linkedList.getLast();

// 删除元素
linkedList.removeFirst();
linkedList.removeLast();

// 作为队列使用
Queue<String> queue = new LinkedList<>();
queue.offer("A"); // 入队
queue.poll(); // 出队

栈(Stack)

用途:后进先出(LIFO)结构
解决问题:需要后进先出逻辑的场景,如撤销操作、括号匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 创建栈 (推荐使用Deque实现)
Deque<Integer> stack = new ArrayDeque<>();

// 压栈
stack.push(1);
stack.push(2);

// 弹栈
int top = stack.pop();

// 查看栈顶元素
int peek = stack.peek();

// 检查是否为空
boolean empty = stack.isEmpty();

队列(Queue)

用途:先进先出(FIFO)结构
解决问题:任务调度、广度优先搜索等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 创建队列 (LinkedList实现)
Queue<String> queue = new LinkedList<>();

// 入队
queue.offer("A"); // 推荐使用offer而不是add(不抛异常)
queue.add("B"); // 可能抛出异常

// 出队
String item = queue.poll(); // 返回并移除队首,队列为空返回null
String item2 = queue.remove(); // 队列为空抛出异常

// 查看队首
String head = queue.peek(); // 队列为空返回null
String head2 = queue.element(); // 队列为空抛出异常

优先队列(PriorityQueue)

用途:按优先级出队的队列
解决问题:需要按特定顺序处理元素的场景,如任务调度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 创建优先队列 (默认最小堆)
PriorityQueue<Integer> pq = new PriorityQueue<>();

// 自定义比较器 (最大堆)
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);

// 添加元素
pq.offer(5);
pq.add(3);

// 获取并移除队首(最小元素)
int min = pq.poll();

// 查看队首
int peek = pq.peek();

集合(Set/HashSet)

用途:不包含重复元素的集合
解决问题:去重、快速成员检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 创建HashSet
Set<String> set = new HashSet<>();

// 添加元素
set.add("Apple");
set.add("Banana");

// 检查存在
boolean hasApple = set.contains("Apple");

// 删除元素
set.remove("Apple");

// 大小
int size = set.size();

// 遍历
for (String item : set) {
System.out.println(item);
}

// 集合运算
Set<String> otherSet = new HashSet<>(Arrays.asList("Banana", "Orange"));

set.retainAll(otherSet); // 交集
set.addAll(otherSet); // 并集
set.removeAll(otherSet); // 差集

有序集合(TreeSet)

用途:保持元素有序的集合
解决问题:需要有序遍历或范围查询的场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 创建TreeSet
Set<Integer> treeSet = new TreeSet<>();

// 自定义排序
Set<Integer> descSet = new TreeSet<>((a, b) -> b - a);

// 添加元素 (自动排序)
treeSet.add(3);
treeSet.add(1);
treeSet.add(2);

// 获取第一个和最后一个
int first = ((TreeSet<Integer>) treeSet).first();
int last = ((TreeSet<Integer>) treeSet).last();

// 范围查询
Set<Integer> subset = ((TreeSet<Integer>) treeSet).subSet(1, 3);

映射(Map/HashMap)

用途:键值对存储结构
解决问题:快速键值查找、关联数据存储

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 创建HashMap
Map<String, Integer> map = new HashMap<>();

// 添加键值对
map.put("Apple", 10);
map.put("Banana", 20);

// 获取值
int appleCount = map.get("Apple");

// 检查键存在
boolean hasApple = map.containsKey("Apple");

// 检查值存在
boolean has10 = map.containsValue(10);

// 删除键值对
map.remove("Apple");

// 遍历键
for (String key : map.keySet()) {
System.out.println(key);
}

// 遍历值
for (Integer value : map.values()) {
System.out.println(value);
}

// 遍历键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

// 获取或默认值
int count = map.getOrDefault("Orange", 0);

// 合并操作
map.merge("Apple", 1, Integer::sum); // 如果存在则相加,否则put 1

有序映射(TreeMap)

用途:保持键有序的映射
解决问题:需要按键顺序遍历或范围查询的场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 创建TreeMap
Map<String, Integer> treeMap = new TreeMap<>();

// 自定义排序
Map<String, Integer> descMap = new TreeMap<>(Comparator.reverseOrder());

// 添加元素 (按键排序)
treeMap.put("Banana", 20);
treeMap.put("Apple", 10);

// 获取第一个和最后一个键
String firstKey = ((TreeMap<String, Integer>) treeMap).firstKey();
String lastKey = ((TreeMap<String, Integer>) treeMap).lastKey();

// 范围视图
Map<String, Integer> subMap = ((TreeMap<String, Integer>) treeMap).subMap("A", "C");

字符串操作(String)

用途:文本处理和操作
解决问题:各种字符串处理需求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 创建字符串
String str = "Hello, World!";

// 基本操作
int length = str.length();
char ch = str.charAt(0);
String sub = str.substring(0, 5); // "Hello"

// 查找
int index = str.indexOf("World"); // 7
int lastIndex = str.lastIndexOf("o"); // 8

// 替换
String newStr = str.replace("World", "Java");

// 分割
String[] parts = str.split(","); // ["Hello", " World!"]

// 连接
String joined = String.join("-", "A", "B", "C"); // "A-B-C"

// 格式化
String formatted = String.format("Name: %s, Age: %d", "Alice", 25);

// 大小写转换
String upper = str.toUpperCase();
String lower = str.toLowerCase();

// 去除空格
String trimmed = " hello ".trim();

// 构建字符串 (高效)
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("World!");
String result = sb.toString();

工具类(Collections/Arrays)

用途:提供集合和数组的常用工具方法
解决问题:简化集合和数组操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Arrays工具类
int[] nums = {3, 1, 2};

Arrays.sort(nums); // 排序
int index = Arrays.binarySearch(nums, 2); // 二分查找
int[] copy = Arrays.copyOf(nums, nums.length);
boolean equal = Arrays.equals(nums, new int[]{1, 2, 3});
String str = Arrays.toString(nums); // "[1, 2, 3]"

// Collections工具类
List<Integer> list = new ArrayList<>(Arrays.asList(3, 1, 2));

Collections.sort(list); // 排序
Collections.reverse(list); // 反转
Collections.shuffle(list); // 随机打乱
int max = Collections.max(list);
int min = Collections.min(list);
Collections.fill(list, 0); // 填充
Collections.swap(list, 0, 1); // 交换

// 不可变集合
List<Integer> unmodifiable = Collections.unmodifiableList(list);
Set<Integer> singleton = Collections.singleton(1); // 单元素集合

这个蓝图集合涵盖了Java中最常用的数据结构和工具方法,可以作为快速参考指南。每个部分都包含了基本操作和典型用法,帮助你快速实现各种数据操作需求。