Java进阶-Collections 工具类

java.util.Collection:集合接口
java.util.Collections:集合工具类,方便集合的操作

  • 把 非线程安全的集合 转成 线程安全

  • 排序

    • 对 List 集合中元素排序,有两种方式:

      • 保证 List 集合中的元素实现了:Comparable 接口

      • Collections.sort(list集合,比较器对象);

    • 对 Set 集合排序:需要将 Set 集合转换成 List 集合 List<String> myList = new ArrayList<>(set);

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CollectionsTest {

public static void main(String[] args) {
// ArrayList 集合不是线程安全的
List<String> list = new ArrayList<>();
// 变成线程安全的
Collections.synchronizedList(list);

// 排序
list.add("ab");
list.add("ad");
list.add("ac");
Collections.sort(list);
for (String s : list) {
System.out.println(s);
// ab
// ac
// ad
}

List<WuGui2> wuGuis = new ArrayList<>();
wuGuis.add(new WuGui2(100));
wuGuis.add(new WuGui2(50));
wuGuis.add(new WuGui2(400));
// 注意:对 List 集合中元素排序,需要保证 List 集合中的元素实现了:Comparable 接口
Collections.sort(wuGuis);
for (WuGui2 wg : wuGuis) {
System.out.println(wg);
// WuGui [age=50]
// WuGui [age=100]
// WuGui [age=400]
}

// 对 Set 集合怎么排序?
Set<String> set = new HashSet<>();
set.add("a");
set.add("c");
set.add("b");
// 将 Set 集合转换成 List 集合
List<String> myList = new ArrayList<>(set);
Collections.sort(myList);
for (String s : myList) {
System.out.println(s);
}

// 这种方式也可以排序
// Collections.sort(list集合,比较器对象);
}
}

class WuGui2 implements Comparable<WuGui2> {
int age;

public WuGui2(int age) {
super();
this.age = age;
}

@Override
public String toString() {
return "WuGui [age=" + age + "]";
}

@Override
public int compareTo(WuGui2 o) {
// TODO Auto-generated method stub
return this.age - o.age;
}
}