一:针对list
通过java.util.Collections的sort方法,有2个参数,第一个参数是list对象,第二个参数是new Comparator<对象类>(){}方法,这个方法实现了compare()方法,具体代码如下所示:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package test2;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class ListSort { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("王五",32)) ; personList.add(new Person("张三",30)) ; personList.add(new Person("赵六",33)) ; personList.add(new Person("李四",31)) ; personList.add(new Person("孙七",33)) ; Collections.sort(personList, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { if(p1.age>p2.age){ return 1; } else if(p1.age<p2.age){ return 0; } else{ return p1.name.compareTo(p2.name) ; // 调用String中的compareTo()方法 } } }); System.out.println(personList); } }class Person { public String name ; public int age ; public Person(String name,int age){ this.name = name ; this.age = age ; } public String toString(){ return "姓名:" + this.name + ";年龄:" + this.age ; }} |
代码执行的结果为:
[姓名:张三;年龄:30, 姓名:李四;年龄:31, 姓名:王五;年龄:32, 姓名:孙七;年龄:33, 姓名:赵六;年龄:33]
二:针对set
要排序的对象所属的类implements Comparable接口,重写了compareTo()方法,具体代码如下所示:
package test1;
import java.util.Set ;
import java.util.TreeSet ;
public class TreeSetDemo4{
public static void main(String args[]){
Set<Person> allSet = new TreeSet<Person>() ;
allSet.add(new Person("赵六",33)) ;
allSet.add(new Person("张三",30)) ;
allSet.add(new Person("王五",32)) ;
allSet.add(new Person("李四",31)) ;
allSet.add(new Person("孙七",33)) ;
System.out.println(allSet) ;
}
}
class Person implements Comparable<Person>{
private String name ;
private int age ;
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public String toString(){
return "姓名:" + this.name + ";年龄:" + this.age ;
}
public int compareTo(Person per){
if(this.age>per.age){
return 1 ;
}else if(this.age<per.age){
return -1 ;
}else{
return this.name.compareTo(per.name) ; // 调用String中的compareTo()方法
}
}
}
代码执行的结果为:
[姓名:张三;年龄:30, 姓名:李四;年龄:31, 姓名:王五;年龄:32, 姓名:孙七;年龄:33, 姓名:赵六;年龄:33]
