import java.util.Arrays;
import java.util.Comparator;
//Comparator 定制排序
/*
* 1. 背景:
* 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,
* 或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,
* 那么可以考虑使用Comparator的对象来排序。
* 2. 重写compare(Object o1, Object o2)方法,比较o1和o2的大小
* 如果方法返回正整数,则表示o1大于o2;
* 如果返回0,表示相等;
* 如果返回负整数,表示o1小于o2。
*
*/
public class ComparatorTest {
public static void main(String[] args) {
String[] arr1 = new String[]{"AA", "ZZ", "CC", "XX"};
Arrays.sort(arr1, new Comparator<String>() {
// 按照字符串从大到小的顺序排列
@Override
public int compare(String o1, String o2) {
if (o1 instanceof String && o2 instanceof String) {
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr1)); // [ZZ, XX, CC, AA]
Goods[] arr2 = new Goods[5];
arr2[0] = new Goods("OPPO", 3199);
arr2[1] = new Goods("Iphone", 6999);
arr2[2] = new Goods("Iphone", 9999);
arr2[3] = new Goods("Xiaomi", 1999);
arr2[4] = new Goods("Huawei", 5999);
Arrays.sort(arr2, new Comparator() {
// 指明商品比较大小的方式:先按照商品名称从低到高,在按照价格从高到低排序
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Goods && o2 instanceof Goods) {
Goods g1 = (Goods) o1;
Goods g2 = (Goods) o2;
if (g1.getName().equals(g2.getName())) {
return -Double.compare(g1.getPrice(), g2.getPrice());
} else {
return g1.getName().compareTo(g2.getName());
}
}
throw new RuntimeException("输入的数据类型不一致");
}
});
System.out.println(Arrays.toString(arr2)); // [Goods{name='Huawei', price=5999.0}, Goods{name='Iphone', price=9999.0}, Goods{name='Iphone', price=6999.0}, Goods{name='OPPO', price=3199.0}, Goods{name='Xiaomi', price=1999.0}]
}
}
class Goods {
private String name;
private double price;
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}