sort arraylist of complex objects alphabetically

前端 未结 2 822
南旧
南旧 2021-02-09 02:16

I know that Collections.sort(myArrayList) can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a

2条回答
  •  北海茫月
    2021-02-09 03:00

    I would create an inner class implementing the Comparator interface:

    public class Car {
    public double horsePower;
    
    class CarHorsePowerComparator implements Comparator {
        @Override
        public int compare(Car car1, Car car2) {
            return Integer.valueOf(car.horsePower).compareTo(Integer.valueOf(car2.horsePower))          }
        }
    }
    

    Now when you want to sort your Car list by horsePower:

    List list = new ArrayList(myCars); //your Car list
    Collections.sort(list, new CarHorsePowerComparator());
    

提交回复
热议问题