JAVA中的Collections集合工具类
- java.util.Collection 是集合接口
java.util.Collections 是集合工具类,方便集合的操作 - Collections.synchronizedList() :将集合转为线程安全的
- Collections.sort() : 对参数列表中的List集合进行排序,Set集合需转成List集合再进行排序
排序的List集合中的自定义类需要实现 java.lang.Comparable 接口
public class CollectionsTest01 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("abz");
list.add("abe");
list.add("aba");
System.out.println(Collections.synchronizedList(list));
Collections.sort(list);
for (String str : list){
System.out.println(str);
}
System.out.println("=======================================");
Set<AnotherWuGui> anotherWuGui = new HashSet<>();
anotherWuGui.add(new AnotherWuGui(1000));
anotherWuGui.add(new AnotherWuGui(3));
anotherWuGui.add(new AnotherWuGui(99));
List<AnotherWuGui> l = new ArrayList<>(anotherWuGui);
Collections.sort(l);
for (AnotherWuGui wugui : l){
System.out.println(wugui);
}
}
}
class AnotherWuGui implements Comparable<AnotherWuGui>{
int age;
public AnotherWuGui(int age) {
this.age = age;
}
public String toString(){
return ("小乌龟的年龄:" + this.age);
}
@Override
public int compareTo(AnotherWuGui o) {
return this.age - o.age;
}
}
[abz, abe, aba]
aba
abe
abz
=======================================
小乌龟的年龄:3
小乌龟的年龄:99
小乌龟的年龄:1000
- 如果直接对Set集合进行排序,编译器会报错: