您的位置:首页 > 其它

自定义comparator

2011-10-31 11:47 78 查看
package j2se;

import java.util.*;

public class TEST
{
public static void main(String[] args)
{
List list = new ArrayList();// 数组列表
list.add(new Person(" 张三", 56, 1.75));// 添加Person类对象到列表中
list.add(new Person("李四", 26, 1.83));
list.add(new Person("王五", 46, 1.65));
System.out.println("排序前列表中的元素:\n" + list);
Comparator comp = new HeightComparator();// 创建比较器的对象
Collections.sort(list, comp);// 根据比较器comp对列表对象排序
System.out.println("按年龄排序后:\n" + list.toString());
//System.out.println("按身高排序后:\n" + list.toString());

}

// 自定义比较器:
public static class HeightComparator implements Comparator
{
int heightCompare;// 按身高比较时返回负整数、0或正整数,以确定大小
Person p1, p2;// 比较器要比较的两个Person对象

public int compare(Object obj1, Object obj2)// 实现接口中的方法
{
p1 = (Person) obj1;
p2 = (Person) obj2;
// 比较两个对象的height大小:将他们包装为Double对象后比较
heightCompare = (Integer)p1.age-(Integer)p2.age;
//heightCompare = new Double(p1.height).compareTo(new Double(
// p2.height));
return heightCompare;// 返回表示两个对象大小的标志,正数表示前一个大
}
}

}
class Person
{
String name;
int age;
double height;

Person(String name, int age, double height)
{
this.name = name;
this.age = age;
this.height = height;
}

public String toString()
{
return name + ":" + age + "岁," + height + "米  ";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: