Error when custom sorting a list:
Collections.sort(roomList, new Comparator<Room>() {
@Override
public int compare(Room r1, Room r2) {
if(r1.getNum() > r2.getNum())
return 1;
return -1;
}
});
Sort in ascending order of the number of people in the classroom. I originally thought that if the number of people in the front is more than the number of people in the back, it will return 1 to exchange positions, otherwise it will return -1, but the operation crashed. After checking the data, it was found that the bottom sorting algorithm of the Collections.sort method was changed from jdk7. , Resulting in the need to return 0 when the two comparison objects are equal, so it should be written like this:
Collections.sort(roomList, new Comparator<Room>() {
@Override
public int compare(Room r1, Room r2) {
if(r1.getNum() > r2.getNum())
return 1;
else if(r1.getNum() < r2.getNum())
return -1;
else
return 0;
}
});
In fact, there is a direct comparison method for integer data, so just write it like this...
Collections.sort(roomList, new Comparator<Room>() {
@Override
public int compare(Room r1, Room r2) {
return Integer.compare(r1.getNum(), r2.getNum());
}
});