I have a list of Student objects, each of them has 3 properties. Color, Size and their names. I want to sort them in ascending order based on their color first, followed by descending order of size and finally, in ascending order of their names. For example, if input is (first line name, second line color and size):
Maria Jose
branco P
Mangojata Mancuda
vermelho P
Cezar Torres Mo
branco P
Baka Lhau
vermelho P
JuJu Mentina
branco M
Amaro Dinha
vermelho P
Adabi Finho
branco G
Severina Rigudinha
branco G
Carlos Chade Losna
vermelho P
I want output to be as:
branco P Cezar Torres Mo
branco P Maria Jose
branco M JuJu Mentina
branco G Adabi Finho
branco G Severina Rigudinha
vermelho P Amaro Dinha
vermelho P Baka Lhau
vermelho P Carlos Chade Losna
vermelho P Mangojata Mancuda
However, after overriding my compareTo() method so that the list is sorted based on what I want, I'm getting output as:
branco P Maria Jose
branco P Cezar Torres Mo
branco M JuJu Mentina
branco G Adabi Finho
branco G Severina Rigudinha
vermelho P Mangojata Mancuda
vermelho P Baka Lhau
vermelho P Amaro Dinha
vermelho P Carlos Chade Losna
As it can be seen, the color and size are sorted correctly however, I'm having trouble with sorting the names. I've tried multiple methods but none works. I can't understand why. Below is my compareTo() method:
public int compareTo(Student student) {
int value1 = color.compareTo(student.color);
if (value1 < 0) {
int value2 = size.compareTo(student.size);
if (value2 < 0) {
int value3 = name.compareTo(student.name);
if (value3 < 0) {
return value3;
}
}
}
return value1;
}
Could someone help me out?
You should go on with comparing the other fields only if the preceding ones are equal, meaning your compareTo
result is 0, not greater than 0.
You can take a look here.