简体   繁体   中英

Can't use custom Comparator in Java

I have problem with implementing my custom comparator for my class:

public class MyProject {
    private static class SuperClass {
        public SuperClass (ArrayList<Car> cars) {
            Collections.sort(cars);
            Collections.sort(cars, new Car.CustomOrder());
        }
    }

    public final static class Car implements Comparable<Car> {
        public Comparator<Car> customOrder() {
            return new CustomOrder();
        }

        public class CustomOrder implements Comparator<Car> {
            public int compare(Car c1, Car c2) {
                // some code
                return 1;
        }
    }
}

I would like to sort cars by custom comparator CustomOrder . I can't find my mistake so please help me.

  1. You have to implement public int compareTo(Car o) in Car class to compile your program.

  2. Collections.sort(cars, new Car().new CustomOrder()); , because CustomOrder is an inner class, not a static nested one. It may be created by the existing reference to the outer class.

An instance of an inner class can exist only within an instance of an outer class and has direct access to the methods and fields of its enclosing instance.


It seems you don't understand inner and nested classes completely. I suggest reading about them on Oracle Tutorials.

As Andrew Tobilko suggested, you have to implement compareTo method in Car class because you want to compare Car objects.

Take a look at the link Java Object Sorting

Also please, write clean code. Your code is hard to read even though it is short.

Try to get rid off the static keyword, that is not a nice way to go and can become easily in a bad design pattern.

you have the class Car, and a list of those somewhere, so independently of if the car implements or not a comparable, you can use an anonymous one and use the fields you need for the sort criteria...

Example:

sorting the list by OrderId (just an String)

public static void main(String[] args) {
    List<Car> myCars = new ArrayList<>();
    myCars.add(new Car(0, "qqweqw", "qwe"));
    myCars.add(new Car(1, "Aqqweqw", "qwe"));
    myCars.add(new Car(2, "Zqqweqw", "qwe"));

    System.out.println("unsorted list" + myCars);
    Collections.sort(myCars, new Comparator<Car>() {

        @Override
        public int compare(Car o1, Car o2) {
            return o1.getOrder().compareTo(o2.getOrder());
        }
    });
    System.out.println("sorted list" + myCars);

}

then as yo can see, no need to declare a new comparator class that binds dependencies to the Car class

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