Collections并不属于集合,是用来操作集合的工具类。
常用方法| 方法 | 说明 |
|---|---|
| public static boolean addAll(Collection super T> c, T… elements) | 给集合对象批量添加元素 |
| public static void shuffle(List> list) | 打乱List集合元素的顺序 |
| public static void sort(List list) | 将集合中元素按照默认规则排序 |
| public static void sort(List list,Comparator super T> c) | 将集合中元素按照指定规则排序 |
若对自定义类排序,则需重写接口。
代码示例
public class CollectionsDemo01 {
public static void main(String[] args) {
List names = new ArrayList<>();
//names.add("楚留香");
//names.add("胡铁花");
//names.add("张无忌");
//names.add("陆小凤");
Collections.addAll(names, "楚留香","胡铁花", "张无忌","陆小凤");
System.out.println(names);
// 2、public static void shuffle(List> list) :打乱集合顺序。
Collections.shuffle(names);
System.out.println(names);
// 3、 public static void sort(List list):将集合中元素按照默认规则排序。 (排值特性的元素)
List list = new ArrayList<>();
Collections.addAll(list, 12, 23, 2, 4);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
下边这个例子和 Java TreeSet自定义类排序 相似,但在List中定义完比较规则还须手动调用sort方法才行。
Test.java
import java.util.*;
public class CollectionsDemo02 {
public static void main(String[] args) {
List apples = new ArrayList<>(); // 可以重复!
apples.add(new Apple("红富士", "红色", 9.9, 500));
apples.add(new Apple("青苹果", "绿色", 15.9, 300));
apples.add(new Apple("绿苹果", "青色", 29.9, 400));
apples.add(new Apple("黄苹果", "黄色", 9.8, 500));
// Collections.sort(apples); // 方法一:可以的,Apple类已经重写了比较规则
// System.out.println(apples);
// 方式二:sort方法自带比较器对象
// Collections.sort(apples, new Comparator() {
// @Override
// public int compare(Apple o1, Apple o2) {
// return Double.compare(o1.getPrice() , o2.getPrice()); // 按照价格排序!!
// }
// });
Collections.sort(apples, ( o1, o2) -> Double.compare(o1.getPrice() , o2.getPrice()) );
System.out.println(apples);
}
}
Apple.java
public class Apple implements Comparable{ private String name; private String color; private double price; private int weight; public Apple() { } public Apple(String name, String color, double price, int weight) { this.name = name; this.color = color; this.price = price; this.weight = weight; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } @Override public String toString() { return "Apple{" + "name='" + name + ''' + ", color='" + color + ''' + ", price=" + price + ", weight=" + weight + '}'; } @Override public int compareTo(Apple o) { // 按照重量进行比较的 return this.weight - o.weight ; // List集存储相同大小的元素 会保留! } }



