简介:

  • 当元素的类型没有实现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(); }

  1. public static void test3() {
  2. String[] arr = new String[]{"AA", "VV", "MM", "GG", "BB"};
  3. Arrays.sort(arr, new Comparator() {
  4. @Override
  5. public int compare(Object o1, Object o2) {
  6. if (o1 instanceof String && o2 instanceof String) {
  7. String s1 = (String) o1;
  8. String s2 = (String) o2;
  9. return -s1.compareTo(s2);//实现从大到小排序
  10. }
  11. throw new RuntimeException("传入的数据类型不一致! ");
  12. }
  13. });
  14. System.out.println(Arrays.toString(arr));
  15. }
  16. public static void test4() {
  17. Goods[] arr = new Goods[5];
  18. arr[0] = new Goods("WTY1", 124);
  19. arr[1] = new Goods("WTY2", 24);
  20. arr[2] = new Goods("WTY3", 326);
  21. arr[3] = new Goods("WTY3", 999);
  22. arr[4] = new Goods("WTY4", 128);
  23. Arrays.sort(arr, new Comparator() {
  24. //指明商品比较大小的方式:
  25. //产品名称从低到高排序,再按照价格从高到低排序
  26. @Override
  27. public int compare(Object o1, Object o2) {
  28. if (o1 instanceof Goods && o2 instanceof Goods) {
  29. Goods g1 = (Goods) o1;
  30. Goods g2 = (Goods) o2;
  31. if (g1.getName().equals(g2.getName())) {
  32. return -Double.compare(g1.getPrice(), g2.getPrice());
  33. } else {
  34. return g1.getName().compareTo(g2.getName());
  35. }
  36. }
  37. throw new RuntimeException("传入的数据类型不一致! ");
  38. }
  39. });
  40. System.out.println(Arrays.toString(arr));
  41. }

}

class Goods {//商品类 private String name; private double price;

  1. public Goods() {
  2. }
  3. public Goods(String name, double price) {
  4. this.name = name;
  5. this.price = price;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public double getPrice() {
  11. return price;
  12. }
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. public void setPrice(double price) {
  17. this.price = price;
  18. }
  19. @Override
  20. public String toString() {
  21. return "Goods{" +
  22. "name='" + name + '\'' +
  23. ", price=" + price +
  24. '}';
  25. }

}

  1. ![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)
  2. <a name="gubq8"></a>
  3. # 案例:
  4. ```java
  5. package mySort;
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.Comparator;
  9. public class DIYsort {
  10. public static void main(String[] args) {
  11. ArrayList<Shape> list = new ArrayList<>();
  12. Circle circle1 = new Circle(2.0);
  13. Circle circle2 = new Circle(3.0);
  14. Triangle triangle1 = new Triangle(1, 2);
  15. Triangle triangle2 = new Triangle(2, 2);
  16. list.add(circle1);
  17. list.add(circle2);
  18. list.add(triangle1);
  19. list.add(triangle2);
  20. Collections.sort(list,new MyComparator());
  21. System.out.println("方法一:==========================");
  22. list.forEach(e -> {
  23. System.out.println(e.getArea());
  24. });
  25. System.out.println("方法二:==========================");
  26. new testt().bj();
  27. }
  28. }
  29. class MyComparator implements Comparator<Shape> {
  30. @Override
  31. public int compare(Shape o1, Shape o2) {//升序排序
  32. return Double.compare(o1.getArea(),o2.getArea());
  33. }
  34. }
  35. class testt implements Comparator<Shape>{
  36. public void bj(){
  37. ArrayList<Shape> list = new ArrayList<>();
  38. Circle circle1 = new Circle(2.0);
  39. Circle circle2 = new Circle(3.0);
  40. Triangle triangle1 = new Triangle(1, 2);
  41. Triangle triangle2 = new Triangle(2, 2);
  42. list.add(circle1);
  43. list.add(circle2);
  44. list.add(triangle1);
  45. list.add(triangle2);
  46. Collections.sort(list,new testt());
  47. list.forEach(e -> {
  48. System.out.println(e.getArea());
  49. });
  50. }
  51. @Override
  52. public int compare(Shape o1, Shape o2) {//降序排序
  53. return -Double.compare(o1.getArea(),o2.getArea());
  54. }
  55. }
  56. interface Shape{
  57. double getArea();
  58. }
  59. class Circle implements Shape{
  60. private double r;
  61. public Circle() {
  62. }
  63. public Circle(double r) {
  64. this.r = r;
  65. }
  66. @Override
  67. public double getArea() {
  68. return Math.PI * r * r;
  69. }
  70. }
  71. class Triangle implements Shape {
  72. private double length;
  73. private double width;
  74. public Triangle() {
  75. }
  76. public Triangle(double length, double width) {
  77. this.length = length;
  78. this.width = width;
  79. }
  80. @Override
  81. public double getArea() {
  82. return length * width;
  83. }
  84. }

image.png