java:Comparator比较器
/*Comparator是java.util包里的一个接口,使用时应该实现导入相应的包,
*再写一个实现了Comparator接口的类,并复写int compare(Object o)方法,
*写出你的判断语句(例如:以下代码是按照年龄的递增顺序排序,年龄相同则按照工资的数目递增排序)
*把这个类添加到Arrays.sort()或Collections.sort()中(例如:定义一个list集合,用来存放对象,可以这样写:Collections.sort(list,new 实现类();))
*/
package test;
import java.util.*;
public class ComparaUser {
private String name;
private int age;
private double salary;
public ComparaUser(){}
public ComparaUser(String name, int age ,Double salary){
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
/*定义一个list集合,存放ComparaUser类型,
使用Array的静态方法asList(T....a)进行添加*/
List<ComparaUser> list = new ArrayList<ComparaUser>(Arrays.asList(
new ComparaUser("张三",24,200.0),
new ComparaUser("李四",28,233.1),
new ComparaUser("王二",25,500.3),new ComparaUser("麻五",24,300.5)));
Collections.sort(list,new Comp());
for(ComparaUser user :list){
System.out.println(user.getName()+" "+user.getAge()+" "+user.getSalary());
}
}
}
class Comp implements Comparator{
//复写Comparator的compara接口
@Override
public int compare(Object o1,Object o2){
ComparaUser user1 = (ComparaUser)o1;/*类型转换,转换成我们所比较的对象*/
ComparaUser user2 = (ComparaUser)o2;
/*按年龄排序,如果第一个user1的年龄大于user2的年龄,则返回 1 (按照升序排列)
小于返回 -1 降序排列 ; 如果相等,则按照工资再比较(参考年龄的比较方式)
*/
if(user1.getAge() > user2.getAge())
return 1;
else if(user1.getAge() < user2.getAge())
return -1;
else {
if(user1.getSalary() > user2.getSalary())
return 1;
else
return -1;
}
}
}