public class TestSort3{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
compareTo
的定义如下:
class Student implements Comparable <Student> {
int rollno;
String name;
int age;
Student(int rollno, String name, int age) {
this.rollno = rollno;
this.name = name;
this.age = age;
}
public int compareTo(Student st) {
if (age == st.age)
return 0;
else if (age > st.age)
return 1;
else
return -1;
}
}
我无法得到在compareTo
方法中比较年龄的逻辑。当调用Collections.sort()
方法时,将调用compareTo()
并且我们已经传递了ArrayList
的实例,因此需要传递Student
类的实例,现在哪个是与之比较的Student
实例?
我已经浏览了与此方法相关的其他stackoverflow链接,但我无法澄清我的疑问,请澄清这一点。
我们假设我们有三名学生,如下所示。
Student vijay = new Student(101, "vijay", 23);
Student ajay= new Student(106, "Ajay", 27);
Student jai= new Student(105, "jai", 21);
vijay
即new Student(101,"Vijay",23)
compareTo()
中调用vijay
方法,它将与ajay
定义的new Student(106,"Ajay", 26 )
进行比较。compareTo()
将在逻辑上小于age
。vijay
对象小于传递给Ajay
方法的对象。this
对象在逻辑上大于传递给compareTo
方法的对象。总体而言, - this
将与compareTo()
进行比较,由于我们的实施,vijay
在逻辑上低于ajay
。 - vijay
将与ajay
and ajay
进行比较,逻辑上将大于jai
对于具有所有组合的元素将发生这种过程,并且最终结果将按年龄递增,即ajay
在java中实现了不同的排序算法,它们将根据与我们的问题无关的特定场景进行选择。
qazxsw poi只是指qazxsw poi被称为的对象。在调用jai
的情况下,可能是该集合的任何成员。
为了减少抽象:
为了使用jai < vijay < ajay
,它必须像这样被调用:
this
其中compareTo
和Collections.sort
都是compareTo
的例子。 a.comparTo(b)
正是这样做的(虽然实际的电话似乎是在a
)。实例使用的细节取决于实现的排序算法以及集合中元素的初始顺序。