简介:
- 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作,那么可以考虑使用Comparator的对象来排序,强行对多个对象进行整体排序的比较。
重写compare(Object o1,Object o2)方法,比较o1和o2的大小:
如果方法返回正整数,则表示o1大于o2; 如果返回0,表示相等; 返回负整数,表示o1小于o2。
可以将 Comparator传递给sort方法(如Collections.sort或Arrays.sort) ,从而允许在排序顺序上实现精确控制。
- 还可以使用Comparator来控制某些数据结构(如有序set或有序映射)的顺序,或者为那些没有自然顺序的对象collection提供排序。 ```java package mySort;
import java.util.Arrays; import java.util.Comparator;
public class CompareTest { public static void main(String[] args) { test3(); test4(); }
public static void test3() {
String[] arr = new String[]{"AA", "VV", "MM", "GG", "BB"};
Arrays.sort(arr, new Comparator() {
@Override
public int compare(Object o1, Object 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(arr));
}
public static void test4() {
Goods[] arr = new Goods[5];
arr[0] = new Goods("WTY1", 124);
arr[1] = new Goods("WTY2", 24);
arr[2] = new Goods("WTY3", 326);
arr[3] = new Goods("WTY3", 999);
arr[4] = new Goods("WTY4", 128);
Arrays.sort(arr, 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(arr));
}
}
class Goods {//商品类 private String name; private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1640265019427-235b0133-a4de-4aa0-b058-c57bf6b4b6da.png#clientId=u602e678a-3d35-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=139&id=u67ec891d&margin=%5Bobject%20Object%5D&name=image.png&originHeight=139&originWidth=1366&originalType=binary&ratio=1&rotation=0&showTitle=false&size=21987&status=done&style=none&taskId=ua3118803-5f60-40a5-b8d4-5833f7cac78&title=&width=1366)
<a name="gubq8"></a>
# 案例:
```java
package mySort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class DIYsort {
public static void main(String[] args) {
ArrayList<Shape> list = new ArrayList<>();
Circle circle1 = new Circle(2.0);
Circle circle2 = new Circle(3.0);
Triangle triangle1 = new Triangle(1, 2);
Triangle triangle2 = new Triangle(2, 2);
list.add(circle1);
list.add(circle2);
list.add(triangle1);
list.add(triangle2);
Collections.sort(list,new MyComparator());
System.out.println("方法一:==========================");
list.forEach(e -> {
System.out.println(e.getArea());
});
System.out.println("方法二:==========================");
new testt().bj();
}
}
class MyComparator implements Comparator<Shape> {
@Override
public int compare(Shape o1, Shape o2) {//升序排序
return Double.compare(o1.getArea(),o2.getArea());
}
}
class testt implements Comparator<Shape>{
public void bj(){
ArrayList<Shape> list = new ArrayList<>();
Circle circle1 = new Circle(2.0);
Circle circle2 = new Circle(3.0);
Triangle triangle1 = new Triangle(1, 2);
Triangle triangle2 = new Triangle(2, 2);
list.add(circle1);
list.add(circle2);
list.add(triangle1);
list.add(triangle2);
Collections.sort(list,new testt());
list.forEach(e -> {
System.out.println(e.getArea());
});
}
@Override
public int compare(Shape o1, Shape o2) {//降序排序
return -Double.compare(o1.getArea(),o2.getArea());
}
}
interface Shape{
double getArea();
}
class Circle implements Shape{
private double r;
public Circle() {
}
public Circle(double r) {
this.r = r;
}
@Override
public double getArea() {
return Math.PI * r * r;
}
}
class Triangle implements Shape {
private double length;
private double width;
public Triangle() {
}
public Triangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}