码迷,mamicode.com
首页 > 编程语言 > 详细

java:Comparable比较器

时间:2016-08-01 20:55:43      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

/*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());
}
}
}

java:Comparable比较器

标签:

原文地址:http://www.cnblogs.com/hui-8-ma/p/5726980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!