/*Comparable 是java.lang中的一个接口,所以是默认导入的,不需要显示的导入。

*如果你先直接在本类中实现排序,那么可以直接实现该接口(例如:public class ComparaUser implements Comparable<ComparaUser>)

*然后复写 int compare(Object o)  提醒:如果在实现接口的时候指明了相应的类型,则这里的Object可以换成对应的类型,避免了强转。

int compareTo(ComparaUser user)

*/

package test;
import java.util.*;
public class ComparaUser implements Comparable<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;
}
@Override
public int compareTo(ComparaUser user){
if(this.getAge() >user.getAge() )
return 1;
else if(this.getAge() <user.getAge() )
return -1;
else{
if(this.getSalary() > user.getSalary())
return 1;
else
return -1;
}
}
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;
}

public static void main(String[] args) {
List<ComparaUser> list = new ArrayList<ComparaUser>(Arrays.asList(
new ComparaUser("张三",28,200.0),
new ComparaUser("李四",24,233.1),
new ComparaUser("王二",25,500.3),new ComparaUser("麻五",24,300.5)));
Collections.sort(list);
for(ComparaUser user :list){
System.out.println(user.getName()+" "+user.getAge()+" "+user.getSalary());
}
}
}

04-14 07:18