Answer the question
In order to leave comments, you need to log in
Why doesn't Collections.sort sort the same way?
In my application there are 4 tabs with data in lists. To sort the data by the time of adding, I use the ordinal numbers of the id of the objects. In three tabs, the data is sorted correctly, but not in the last one.
So here is the code
Collections.sort(allMentorsList, new Comparator<OneMentorClass>() {
@Override
public int compare(OneMentorClass o1, OneMentorClass o2) {
return o2.getMentorID().compareTo(o1.getMentorID());
}
});
Collections.sort(allLawyersList, new Comparator<OneLawyerClass>() {
@Override
public int compare(OneLawyerClass o1, OneLawyerClass o2) {
return o2.getLawyerID().compareTo(o1.getLawyerID());
}
});
public class OneMentorClass {
private String mentorID;
public OneMentorClass(String mentorID) {
this.mentorID = mentorID;
}
public String getMentorID() {
return mentorID;
}
}
public class OneLawyerClass {
private String lawyerID;
public OneLawyerClass(String lawyerID) {
this.lawyerID = lawyerID;
}
public String getLawyerID() {
return lawyerID;
}
Answer the question
In order to leave comments, you need to log in
Your ID is String. He compares them in lexicographical order because he doesn't know they are numbers. Therefore 25 is greater than 100, for example (because 2 is greater than 1). You look - you got IDs in descending order of the first digit. You need to parse them as numbers or write your own comparator, which will compare correctly.
In addition, when you have Comparable elements to sort, you don’t need to write your own comparator for the reverse order at all. There is Collections.reverseOrder().
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question