public String name;
public Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Student o) {
return name.compareTo(o.name);
}
}`
`class Main{
public static void main(String[] args){
Student michael = new Student("michael");
Student[] students = {new Student("Jim"),new Student("Pam"),new Student("Dwight")};
Arrays.sort(students);
System.out.println(Arrays.toString(students));
System.out.println("results are :- " + michael.compareTo(students[2]));
}
}`
Result :-
[Dwight, Jim, Pam]
results are :- 29``
I have a doubt regarding compareTo method. How is it functioning? I have just written a return statement which is itself calling compareTo method. What is happening here? Can someone let me know?
#compareTo method
5 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @tulip flax! Please use
/closeor theClose Postbutton above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Please format your code to make it more readable.
For java, it should look like this:
````java
public void foo() {
}
````
The compareTo() method you're calling is the one of class String. The class you're making isn't class String, it's class Student.
You want Students to be sorted by their names, which are String, so you delegate class Student's compareTo() to class String's compareTo()