简体   繁体   中英

comparable interface separated sorting for instances

The procedure:

1) I want to show all bus first, and then taxi.

2) Then i would like to sort all bus or taxi by model ,brand, price by alphabetical order or ascending order.

Question:

1) How can i show the bus records first and taxi records behind.

2) I don't know how to sort only bus or taxi records by their parameter. ( i used to sort all the records together. It makes me crazy)

3) More importantly , do i only need to do the sorting with the superclass "class Car implements comparable " ? one class only have one " public int compareTo (Car other)" ?

The expected result should be:

(Many different records for bus------ not yet sorted)

Model:

Brand:

Price:

numberofdoor:

(Many different records for taxi --- not yet sorted)

Model:

Brand:

Price:

colour:

   public static void main(String[] args) {
   ArrayList<Car> tablets = new ArrayList<Car>();

     .....something ignored....


    Collections.sort(Car);

    for (Car cars : Car) {
        System.out.println(Car);
    }



 class Car implements comparable <Car>
 {
 private String Model;
 private String Brand;
 private int Price;
 public Car (String Model , String Brand , int Price)
 {
     this.Model = Model;
     this.Brand = Brand;
     this.Price = Price;
 }


 .....Some Get and PrintInfo Method here.....


      public int compareTo (Car other)
      {
      }
 }


  class bus extends Car 
   {
  Private String colour;
  public bus ((String Model , String Brand , int Price , String colour)
  {
      super (Model, Brand, Price);
      this.colour= colour;
  }

   .......some Get and PrintInfo method here......


   }


   class taxi extend Car 
   {
   private int numberofdoor;
   public bus (String Model , String Brand , int Price , int numberofdoor)
   {
       super (  Model , Brand ,  Price );
       this.numberofdoor = numberofdoor;
   }


  .......some Get and PrintInfo method here......
   }

You can use your own Comparator like this:

Collections.sort(cars, new Comparator<Car>() {
    @Override
    public int compare(Car car1, Car car2) {
        // Both objects are belongs same class
        if (car1 instanceof Bus && car2 instanceof Bus ||
                     car1 instanceof Taxi && car2 instanceof Taxi) {
             // Here compare some property, e.g. model property:
             return car1.getModel().compareTo(car2.getModel());
        } else {
             // Here we say that Taxi object greater than Bus object
             return car1 instanceof Taxi ? 1 : -1;
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM