How do I use Comparator to define a custom sort order?

后端 未结 9 1152
生来不讨喜
生来不讨喜 2020-11-22 08:40

I want to develop a sorting demo for car list. I am using data table to display car list. Now actually I want to sort the list by car color. Here it is not sort by alphabeti

9条回答
  •  我在风中等你
    2020-11-22 09:25

    I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

    public enum PaintColors {
        SILVER, BLUE, MAGENTA, RED
    }
    

    and

     static class ColorComparator implements Comparator
     {
         public int compare(CarSort c1, CarSort c2)
         {
             return c1.getColor().compareTo(c2.getColor());
         }
     }
    

    You change the String to PaintColor and then in main your car list becomes:

    carList.add(new CarSort("Ford Figo",PaintColor.SILVER));
    
    ...
    
    Collections.sort(carList, new ColorComparator());
    

提交回复
热议问题