Java Notes

Java笔记

2024.12.28

基础数据结构

1
2
3
4
5
6
7
8
9
10
11
// Stack 栈
Stack<E> stack = new Stack<>();
// push(E item), pop(), peek() 查看栈顶元素,isEmpty() 栈是否为空

// Queue 队列
Queue<E> queue = new LinkedList<>();
// add(E e) / offer(E e), poll() 出队,返回并移除队首元素,peek() 查看队首元素

// Array 数组
int[] arr = new int[size];
// 长度arr.length, Arrays.sort(arr) 排序,Arrays.toString(arr) 转换为字符串
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 类似Vector
ArrayList<Integer> list = new ArrayList<>();
// add() 末尾添加元素,remove(int index) 删除指定索引处元素
// set(index, element) 替换指定索引处元素,get(index) 获取指定索引处元素
// size() list.size() 获取大小
// Integet[] arr = list.toArray(new Integet[0]);


// LinkedList 链表
LinkedList<E> list = new LinkedList<>();
// add(), addFirst(), addLast(); remove(), removeFirst(), removeLast()
// 获取元素get(index),getFirst(), getLast()

// PriorityQueue 优先队列
PriorityQueue<E> pq = new PriorityQueue<>();
// add(E e), poll() 取出优先级最高元素,peek() 查看优先级最高元素
// 使用自定义比较器:new PriorityQueue<>(Comparator<E>)

// Set 集合
HashSet<E> set = new HashSet<>();
// add(E e), remove(E e), contains(E e) 判断是否存在
// 遍历 for(E e : set)

// Map 映射
HashMap<K, V> map = new HashMap<>();
// 添加键值对put(key, val), 获取值get(key), 判断是否包含键key contains(key)
// 遍历 for(Map.Entry<K, V> entry : map.entrySet())

// String
String str1 = "Hello";
String str2 = "World!";
String res = str1 + str2; // 拼接
String res = str1.substring(0, 5); // 从开始索引0到结束索引5,<= 5
String res = str1.replace("H", "h"); // str1 = "hello"

String str = "a,b,c";
String[] parts = str.split(","); // 分割,parts = [a, b, c]

实用方法

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
// 数组长度
int []arr = {1, 2, 3};
System.out.println(arr.length);

// sort()函数
Arrays.sort(arr); // 升序排序

Arrays.sort(arr, (a, b) -> b - a); // 按长度降序排序
System.out.println(arr); // 输出: [3, 2, 1]

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
Collections.sort(list); // 升序排序
list.sort((a, b) -> b - a); // 降序排序

// string 2 int
String str = "123";
int num = Integer.parseInt(str);
double d = Double.parseDouble("123.45");
String nstr = Integet.toString(num);

// for循环
for(int num : nums)

// lambda表达式
(parameter) -> expression
(parameter) -> { statement; }

// b - a > 0,那么b在a前;若b - a < 0, 那么a在b前
Comparator<Integer> cmp = (a, b) -> b - a;
int []arr = {1, 2, 3};
Arrays.sort(arr, cmp); // arr = {3, 2, 1}