문제

I've been having problems about this:

public class Student implements Comparable {
    private int id;
    private String name;



    public int compareTo(Student other) {
       return 1; // This is just an example value

    }
}

This program doesn't compile, as it says that it doesn't override the method "compareTo()" . Now why is that?

But if I use the following class header

public class Student implements Comparable<Student>{...}

it works fine. I need some explanation about this. By the way a lot of internet examples of the "Comparable" interface use the first class header, I mean without the Comparable.

도움이 되었습니까?

해결책

Look at the source code of Comparable. With implements Comparable the method within student would be

public int compareTo(Object other) { ...

Using generics Comparable the method is like you wrote it.

By the way the compiler should have given you a helpful explanation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top