Java中Collections类的排序sort函数两种用法

java中的Colletions类主要实现列表List的排序功能。根据函数参数的传递,具体的排序可以分为 :

1.  自然排序(natural ordering)。

函数原型:sort(List<T> list)
说明:参数是要参与排序列表的List对象                                                               
实例说明:参与排序的列表的元素Student必须实现Comparable接口的
public int compareTo(Object o) 方法,在里面写对比的原则。
然后调用Colletions.sort(排序对象的列表)    
请看如下示例:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
class ArrayListTest{
public static void printElements(Collection c){
Iterator it = c.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static void main(String[] args){
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(2,"aora"));
al.add(new Student(1,"longyu"));
al.add(new Student(3,"goso"));
Collections.sort(al);
printElements(al);
}
}
class Student implements Comparable{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
public int compareTo(Object o) {
Student s = (Student)o;
return num > s.num ? 1 : (num == s.num ? 0 : -1);
};
public String toString(){
return "num = " + this.num + ",name = " + this.name;

}

2.  实现比较器(Comparator)接口。

函数原型:sort(List<T> list, Comparator<? super T> c)
说明:第一个参数同左,第二个参数是构建对比规则的对比器Comparator。
实例说明(如下):在参与排序的列表的元素Student中写一个内部类作为
Student的对比器,这个对比器要实现Comparator接口的public int compare(Object o1,
Object o2)方法,然后调用Colletions.sort(排序对象的列表,对比器)  

请看如下示例:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Comparator;
class ArrayListTest{
public static void printElements(Collection c){
Iterator it = c.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static void main(String[] args){
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(2,"qingan"));
al.add(new Student(1,"longyu"));
al.add(new Student(3,"goso"));
al.add(new Student(2,"aora"));
Collections.sort(al,new Student.studentComparator());
printElements(al);
}
}
class Student{
int num;
String name;
Student(int num,String name){
this.num = num;
this.name = name;
}
static class studentComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);
                        // 注意:此处在对比num相同时,再按照name的首字母比较。
if(result == 0){
result = s1.name.compareTo(s2.name);
}
return result;


public String toString(){
return "num = " + this.num + ",name = " + this.name;

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值