Java比较对象大小两种常用方法

引入原因:

Java中的对象,正常情况下,只能进行比较:== 或!= ,不能使用 < 或 > ,但是在开发时需要用到比较对象的大小

1.Comparable接口的使用(自然排序)

1.像String 、包装类等实现了Comparable接口,重写了compareTo()方法,给出了比较两个对象大小的方法

2.像String 、包装类等重写了compareTo()方法后,默认执行了从小到大的排序

3.重写compareTo()的规则:

如果当前对象this大于形参对象obj,则返回正整数,如果当前对象this小于形参对象obj,则返回负整数。如果当前对象this等于形参对象obj,则返回零。

4.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo()方法, 在compareTo()方法中指明如何排序

String类的自然排序实现举例:

@Test
  public void test1(){
    String[] arr=new String[] {"GG","MM","AA","CC","DD","KK"};
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr)); //[AA, CC, DD, GG, KK, MM]
  }

自定义类的自然排序举例: 

@Test
  public void test2(){
    Goods[] arr=new Goods[4];
    arr[0] = new Goods("lenovoMouse",34);
    arr[1] = new Goods("dellMouse",66);
    arr[2] = new Goods("xiaomiMouse",50);
    arr[3] = new Goods("hahaMouse",66);
 
    Arrays.sort(arr);
    System.out.println(Arrays.toString(arr));
    /*
    运行结果:
    [Goods{name='lenovoMouse', price=34.0}, Goods{name='xiaomiMouse', price=50.0},
     Goods{name='dellMouse', price=66.0}, Goods{name='hahaMouse', price=66.0}]
    */
  }

Goods商品类的实现代码:

public class Goods implements Comparable {
  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 void setName(String name) {
    this.name = name;
  }
 
  public double getPrice() {
    return price;
  }
 
  public void setPrice(double price) {
    this.price = price;
  }
 
  @Override
  public String toString() {
    return "Goods{" +
        "name='" + name + '\'' +
        ", price=" + price +
        '}';
  }
 
  //指明商品比较大小的方式,按照价格从低到高排序,如果出现价格相同的,再按照产品名称从低到高排序
  @Override
  public int compareTo(Object o) {
    if(o instanceof Goods ){
      Goods goods =(Goods)o;
      if (this.price > goods.price) {
        return 1;
      }else if(this.price < goods.price){
        return -1;
      }else
        //return 0;
        return this.name.compareTo(goods.name);
    }
    throw new RuntimeException("传入的数据类型不一致");
  }
}

2.Comparator接口的使用 (定制排序)

2.1引入原因:当元素的类型没有实现java.lang.Comparable借口而又不方便修改代码,或者实现了java.lang.Comparable接口的排序规则不适合当前的操作可以考虑使用Comparator的对象来实现排序。

2.2重写compare(Object o1,Object o2)方法,比较o1和o2的大小,如果方法返回正整数,则表示o1大于o2,如果返回0,表示二者相等,如果返回负整数,表示o1小于o2.

举例一:

@Test
 public void test1(){
   String[] arr=new String[] {"GG","MM","AA","CC","DD","KK"};
   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);
       }
       //return 0;
       throw new RuntimeException("输入的数据类型不一致");
     }
   });
   System.out.println(Arrays.toString(arr)); //[MM, KK, GG, DD, CC, AA]
 }

举例二:

@Test
  public void test2(){
    Goods[] arr=new Goods[5];
    arr[0] = new Goods("lenovoMouse",34);
    arr[1] = new Goods("dellMouse",66);
    arr[2] = new Goods("xiaomiMouse",50);
    arr[3] = new Goods("hahaMouse",66);
    arr[4] = new Goods("hahaMouse",166);
 
    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));
    /*
    运行结果:
    [Goods{name='dellMouse', price=66.0}, Goods{name='hahaMouse', price=166.0},
    Goods{name='hahaMouse', price=66.0}, Goods{name='lenovoMouse', price=34.0},
    Goods{name='xiaomiMouse', price=50.0}]
    */
  }

Java比较对象大小两种常用方法

扫一扫手机访问