/**
* 需求:
* 用户类具有String name、int score、int time等属性,请首先按照score降序排序,
* 如果score相同,则按照time升序排序,如果time相同,则按照name降序排序。
*/
package com.hung._11_12;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort {
private List users = new ArrayList<>();
private UserManager userManager = null;
public Sort(){
this.userManager = new UserManager();
this.initUsers();
this.sort(this.users);
}
private void initUsers(){
users.add(new User("Cung" ,65 ,90 ));
users.add(new User("Vung" ,65 ,55 ));
users.add(new User("Dung" ,65 ,55 ));
users.add(new User("Eung" ,94 ,75 ));
users.add(new User("Cung" ,93 ,75 ));
}
private void sort(List list){
Collections.sort(list, userManager);
}
private void disPlay() {
for (User user : users) {
System.out.println(user);
}
}
public static void main(String[] args) {
new Sort().disPlay();
}
}
/**
@author Hung
用户类
*/
class User {
private String name = null;
private int score = 0;
private int time = 0;
public User(String name , int score , int time){
this.name = name;
this.score = score;
this.time = time;
}
@Override
public String toString() {
return "Name: "+this.getName()+" Score: "+this.getScore()+" Time: "+this.getTime();
}
public String getName(){
return this.name;
}
public int getScore(){
return this.score;
}
public int getTime(){
return this.time;
}
}
/**
User的工具类
*/
class UserManager implements Comparator {
@Override
public int compare(User u1 , User u2){
//如果分数相同则按照时间排序
if(u1.getScore() != u2.getScore())
return u2.getScore()-u1.getScore();
//如果时间相同则按照姓名排序
else if(u1.getTime()!=u2.getTime())
return u1.getTime()-u2.getTime();
else
return u1.getName().compareTo(u2.getName());
}
}