数组排序比较器方法始终进行默认比较 [英] Array Sort Comparator method always does a default comparison
问题描述
我有一个班级学生-int年龄,int身高和姓名;
I have a class student - int age , int height and Name;
我有n个学生班级的对象,我尝试先按年龄排序(如果有平局,然后按身高排序),如果有平局,则对名称进行随机排序.
I have n objects of the student class and I try to sort then first by age , if there is a tie then by height , if there is a tie randomize name .
我上课
class StudentComparator implements Comparator{
public int compare(Object 1, Object2)
{
// Logic
}
}
我有一个主要班级
class StudentSorter {
// Initialise student objects etc
// Have an array of students: students[]
Array.Sort(students,new StudentComparator() )
// print values
}
我面临的问题是Output与我在StudentComparator类的比较器方法中的逻辑不相似. 逻辑是:
The problem I am facing is that Output does not resemble the logic I have in comparator method of the StudentComparator class. Logic is :
if(Student1.age > student2.age)
{
return 1;
}
else if(Student1.age < student2.age)
{
return -1;
}
else
{
if(Student1.height > Student2.height)
return 1;
else if(Student1.height < Student2.height)
return -1;
else
return 0;
}
输入: 15 6约翰 16 5山姆 17 6鲁尼
Input : 15 6 John 16 5 Sam 17 6 Rooney
输出:(无论我如何处理逻辑甚至对其进行评论)
output: (no matter How I play around with logic or even comment it)
17 6 Rooney
16 5 Sam
15 6 John
可能是什么问题?
推荐答案
您可以尝试以下方法:
public int compare(Student s1, Student s2)
{
return s1.age == s2.age ? s1.height - s2.height : s1.age - s2.age;
}
这篇关于数组排序比较器方法始终进行默认比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!