java 自定义和使用比较器

import java.util.*;
public class UseComparator {
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());

}
//自定义比较器:
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=new Double(p1.height).compareTo(new Double(p2.height));
return heightCompare;//返回表示两个对象大小的标志,正数表示前一个大
}
}

}


public 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+"米 ";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值