Search code examples
javaclassinterfacecomparable

How do I tell Java that an interface implements Comparable?


I have an interface named IDebt, and a class implementing said interface named Debt.

I also have a list made of objects implementing the IDebt interface:

List<IDebt> debtList = new ArrayList<IDebt>();

The class Debt implements Comparable, but when I do Collections.sort(debtList) I get an error, because Java has no way to know that the object implementing IDebt as such implements Comparable.

How can I solve this?


Solution

  • You can do this:

    public static interface MyInterface extends Comparable<MyInterface> {
    
    }
    
    public static class MyClass implements MyInterface {
    
        @Override
        public int compareTo(MyInterface another) {
            return 0; //write a comparison method here
        }
    }
    

    Then

    List<MyInterface> test = new ArrayList<>();
    Collections.sort(test);
    

    will work

    Update: also for sorting maybe this makes more sense:

    Collections.sort(test, new Comparator<MyInterface >() {
            @Override
            public int compare(MyInterface lhs, MyInterface rhs) {
                return 0;
            }
        });