I'm learning about sorting Java objects through the Internet.
The code below is sorted in ascending order by gender, age, and name, but I don't understand the logic of gender sorting. Why is the gender "m" element leading the list?Does it mean that if the compareTo method returns 1, it will be in ascending order?
public class SmartEnergy {
public static void main(String[]args) {
List<Student>students=new ArrayList<>();
students.add(new Student("Inoue Naomi", 24, 'f', 158));
students.add(new Student("Takahashi Tatsuya", 23, 'm', 176));
students.add(new Student("Inoue Naomi", 27, 'm', 164));
students.add(new Student("Megumi Enomoto", 24, 'f', 162));
students.add(new Student("Enomoto Taku", 24, 'm', 178));
students.add(new Student("Sakura Takaharu",26, 'f',163));
// Sort by gender, age, and name in ascending order
Collections.sort(students, new Comparator<Student>(){
public int compare (Student student1, Student student2) {
int temp = 0;
if(student1.getSex()=='m'&student2.getSex()=='f')
temp=-1;
if(student1.getSex()=='f'&student2.getSex()=='m')
temp = 1;
if(temp==0){
temp=student1.getAge() -student2.getAge();
if(temp==0)
temp=student1.getName().compareTo(student2.getName());
}
return temp;
}
});
for (Student:students) {
System.out.println(student.getName()+", "+student.getAge()+", "
+ student.getSex()+", "+student.getHeight()));
}
}
}
Sort using the compare method of Comparator passed by the second argument of sort
.
The compare
method determines the order (large or small) of the two objects passed.
Compare the two arguments for ordering.Returns a negative integer if the first argument is less than the second argument, 0 if both are equal, or a positive integer if the first argument is greater than the second argument.
There is a rule that should be followed, so
if(student1.getSex()=='m'&student2.getSex()=='f')
temp=-1;
Setting -1
to temp
in this code means
If the gender of the first object student1
is m
and the gender of the second object student2
is f
student1<student2
.
In other words, men are small objects.
Therefore, a small object with a gender of m
comes before it.
if(temp==0){
temp=student1.getAge() -student2.getAge();
if(temp==0)
temp=student1.getName().compareTo(student2.getName());
The order of the same gender is age.
If the ages are the same, it means to order by name.
The meaning of temp
is (or is a positive integer) of the part already quoted.
Suppose 1
student1>student2
means
sort
uses the order information of those two objects to sort them.
© 2024 OneMinuteCode. All rights reserved.