`

java 使用 Comparator接口 进行多种情况排序

阅读更多

 java.util.Comparator接口容易被实现并使用,但是在Comparator的API文档里有些部分还是应当仔细阅读一下的。
实现了Comparator接口的类可以传给例如Collections.sort这样的排序方法。它们也可以被Map或者Set类使用,用来保证Map或者Set里的元素始终是按某种顺序排列的。TreeSet和TreeMap就是这样的类。

在Comparator接口里,只有一个方法是需要实现的:

int compare(Object o1,Object o2);如果o1小于o2,返回一个负数;如果o1大于o2,返回一个正数;如果他们相等,则返回0;

这些就是通常为了完成比较所要做的一切,但是在Comparator接口的契约里还有别的义务。

首先,compare方法一定要是对称的,意思是compare(a,b)返回的结果要跟compare(b,a)相反。相反的结果意味着,要么返回的值带有不同的正负号,要么都是0。注意,象compare(a,b)返回4而compare(b,a)返回-2这样的情况是合法的。方法里常常可能抛出异常,在这个方法里抛出异常也要是对称的。如果调用compare(a,b)时抛出了一个ClassCastException异常,那么调用compare(b,a)时也必须抛出一个ClassCastException异常。

 

public abstract class Car {
 
  protected String name;
 
  protected int price;
 
  protected String Brand;
 
   public abstract double depriciation();
 
}

 

 

 

public class CarComoarator implements Comparator<Car> {

 
 public int compare(Car o1, Car o2) {
  int a = (int)(((Car)o1).depriciation());
  int b = (int)(((Car)o2).depriciation());
  return b-a;
 }

}

 

 

public class NegonCar extends Car {

 
 public double depriciation() {
  
  return this.price * 0.10;
 }

 

}

 

 

public class SUVCar extends Car {

 
 public double depriciation() {
  
  return this.price * 0.15;
 }  

}

public class Test {

 

 

public static void main(String[] args) {
  
    Car car1 = new SUVCar();
    car1.price = 40000;
    Car car2 = new   NegonCar();
    car2.price = 30000;
    List<Car> beforeSort = new    ArrayList();
    beforeSort.add(car1); beforeSort.add(car2);
    for  (Iterator iterator = beforeSort.iterator(); iterator.hasNext();) {
    Car car = (Car) iterator.next();
    System.out.print(car.depriciation());
    }
    System.out.println();
    sortCar(beforeSort); for (Iterator iterator = beforeSort.iterator();
    iterator.hasNext();) { Car car = (Car) iterator.next();
    System.out.print(car.depriciation()); }
     

 }

 
 public static void sortCar(List list) {

  Collections.sort(list, new CarComoarator());

 }

 

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics