سؤال

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