快捷键:一次性将相同变量名改名字: 选中要改的变量名shift + F6
package com.itheima.d2_params;
import java.util.*;
public class CollectionsDemo02 {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
// 这是正常添加集合元素
// names.add("楚留香");
// names.add("胡铁花");
// names.add("张无忌");
// names.add("陆小凤");
// 1. 现在可以使用Collections的工具类的addAll API 即可实现一行代码添加全部元素
Collections.addAll(names,"楚留香","胡铁花","张无忌","陆小凤"); // elements前面有三个点:表示可变参数
System.out.println(names);
// 2. public static void shuffie(List<?> list):打乱集合顺序
Collections.shuffle(names); // 每次编译就会打乱一次顺序 Shuffle [ˈʃʌfl] 洗牌的意思
System.out.println(names);
// 3. public static <T> void sort(List<T> list): 将集合中元素按照默认排序规则排序 (排值特性的元素)
List<Integer> list = new ArrayList<>();
Collections.addAll(list,12,23,2,4);
// list.add(23);
// list.add(24);
// list.add(12);
// list.add(8);
System.out.println(list); // 现在打印是没有排序的 [12, 23, 2, 4]
Collections.sort(list); // 使用Collections工具类的sort Api可以排序
System.out.println(list); // 排序成功了的 // [2, 4, 12, 23]
// public static <T> void sort(List<T> list.Comparator<? super T> c);
// 将集合中元素按照规则排序,自带比较器
List<Apple> 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类已经重写了比较规则(compareTo)
// System.out.println(apples);
// 方式二: sort方法自带比较器对象Comparator 其实方法是差不多的,都是定义比较器
Collections.sort(apples, new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return Double.compare(o1.getPrice() , o2.getPrice());
}
});
System.out.println(apples);
}
}
package com.itheima.d2_params;
// 使用Apple类 去实现接口的某种功能 // Comparable这里是比较功能的接口,传入Apple对象
public class Apple implements Comparable<Apple>{
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;
}
// 写javabean现在一般会再加一个toString方法(重写),如果有引用类型可以直接打印其内容
@Override
public String toString() {
return "Apple{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
", price=" + price +
", weight=" + weight +
'}';
}
/**
* 方式一: 类自定义比较规则
* @param o the object to be compared.
* @return
*/
@Override
public int compareTo(Apple o) {
// 按照重量进行比较的
// this代表你本身这个对象,o表示你放到参数里的对象 这里的this相当于o1 , o相当于o2
// this是现在定义的这个类的学生对象,o是拿来比较输入的学生对象
return this.weight - o.weight; // 升序排序
// return this.weight - o.weight >= 0 ? 1 : -1; // 保留去重复的元素
}
}