在进行对象数组排序的过程中需要使用到比较器,比较器有两个:Comparable和Comparator
java.lang.Comparable:是在类定义是时候默认实现好的接口,里面提供有一个compareTo()方法用于大小比较
java规定:假如a和b是实现Comparable接口类创建的两个对象,
当a.compareTo(b)<0时,称a小于b;
a.compareTo(b)>0时,称a大于b;
a.compareTo(b)==0时,称a等于b。
java.util.Comparator:需要单独定义一个排序的比较规则类,里面有两个方法compare(),equals()
优先使用Comparable
package com.wzy.main; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import org.omg.PortableInterceptor.Interceptor; class People implements Comparable{ People(String name,int age){ this.name = name; this.age = age; } private String name; private int age; public int getAge() { return age; } public String getName() { return name; } @Override public String toString() { return "name="+name+", age="+age; } @Override public int compareTo(Object o) { People p = (People)o; return p.age-this.age; } } //使用Comparator比较器 class PersonComparator implements Comparator { @Override public int compare(Object one, Object another) { return ((People)one).getAge()-((People)another).getAge(); } } public class Test01 { public static void main(String[] args) { List<People> list = new ArrayList<People>(); list.add(new People("aaa", 15)); list.add(new People("bbb", 10)); list.add(new People("ccc", 16)); list.add(new People("ddd", 13)); list.add(new People("eee", 19)); //Collections.sort(list);//按照age进行排序,使用Comparable Collections.sort(list, new PersonComparator());//使用Comparator比较器,按照age进行排序 Iterator<People> interceptor = list.iterator(); while(interceptor.hasNext()){ System.out.println(interceptor.next()); } } }
时间: 2024-10-31 07:32:24