【问题标题】:comparable interface separated sorting for instances实例的可比接口分离排序
【发布时间】:2016-03-18 01:30:57
【问题描述】:

程序:

1) 我想先显示所有巴士,然后显示出租车。

2) 然后我想按型号、品牌、价格按字母顺序或升序对所有公共汽车或出租车进行排序。

问题:

1) 如何先显示公交车记录,然后显示出租车记录。

2) 我不知道如何按参数仅对公共汽车或出租车记录进行排序。 (我曾经将所有记录排序在一起。这让我发疯)

3) 更重要的是,我是否只需要使用超类“类 Car 实现可比较”进行排序?一个类只有一个“public int compareTo(Car other)”?

预期结果应该是:

(总线的许多不同记录------尚未排序)

型号:

品牌:

价格:

门数:

(出租车的许多不同记录 --- 尚未排序)

型号:

品牌:

价格:

颜色:

   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......
   }

【问题讨论】:

    标签: java comparable implements


    【解决方案1】:

    您可以像这样使用自己的比较器:

    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;
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2016-09-05
      • 2012-11-01
      • 2014-03-04
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多