自定义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 + "米 "; } }
相关文章推荐
- java 第八篇 使用comparator实现自定义排序
- Java自定义比较器Comparator
- TreeMap使用自定义Comparator
- TreeSet自定义比较器实现Comparator接口,覆盖Compare方法
- Hadoop自定义排序和自定义数据类型使用(setSortComparatorClass和setGroupingComparatorClass)
- java comparable comparator 比较器的使用 及 自定义比较器
- TreeSet中自定义Comparator实现降序
- List<Map>自定义Comparator在jdk1.7中出现问题
- Java数组排序中Comparator接口实现自定义排序
- 使用Comparable、Comparator接口实现对对象数组、List集合自定义排序
- java学习(十六):对象的自定义比较,Comparator和Comparable
- 浅谈Java的Comparator接口实现自定义排序Arrays.sort()
- 自定义数据排序(Comparable,Comparator)JAVA126
- SortedMap接口的实现类TreeMap介绍和实现Comparator自定义比较器(转)
- 关于comparable与comparator的用法(即自定义集合框架用法 )
- 自定义Comparator比较String字符串
- Hadoop自定义排序和自定义数据类型使用(setSortComparatorClass和setGroupingComparatorClass)
- Android自定义Comparator,实现List按时间排序
- Comparator自定义对比
- Android记录14--自定义Comparator,实现List按时间排序