love fish大鹏一曰同风起,扶摇直上九万里

常用链接

统计

积分与排名

friends

link

最新评论

java 集合类的排序(转)

java 集合类的排序主要是用Collections.sort方法,Collections和Collection是不一样的,前者是类,后者是接口,在这里,我主要是想说明它的sort方法的几种类型,
提示:实现接口的方法时,只需要比较两个数,大的返回1,相等返回0,小于返回-1。简单的说就是在方法里这样写:num>s.num?1:(num==s.num?0:-1); num是被比较的数,s.num是比较的数,

1.Collection.sort(List arg0);
这种是最简单的一种排序方法,只需要实现他的Comparable 接口及实现public int compareTo(Object arg0)方法即可。
2.Collection.srot(List arg0,Comparator arg1);
这种加入了比较器,具有更大的灵活性,便于管理,比较器可作为内部静态类的,以便于管理。比较器必须实现Comparator接口,具体可参照下列代码:

package com.gc.list;
import java.util.*;
public 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 a1=new ArrayList();
  /*
  a1.add("zhangsan");
  a1.add("lisi");
  a1.add("wangwu");
  */
  /*
  a1.add(new Point(1,1));
  a1.add(new Point(2,2));
  a1.add(new Point(3,3));
  
  for(int i=0;i<a1.size();i++){
   System.out.println(a1.get(i));
  }
  Object[] objs=a1.toArray();
  for(int i=0;i<objs.length;i++){
   System.out.println(objs[i]);
  }
  
  List l=Arrays.asList(objs);
  System.out.println(l);*/
  //l.add("chuyang");
  //l.set(0,new Point(4,4));
  /*
  Iterator it=a1.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  */
  Student s1=new Student(4,"zhangsan");
  Student s2=new Student(2,"lisi");
  Student s3=new Student(3,"wangwu");
  Student s4=new Student(4,"mybole");
  
  a1.add(s1);
  a1.add(s2);
  a1.add(s3);
  a1.add(s4);
  //Collections.sort(a1);
  Collections.sort(a1,new Student.StudentComparator());
  printElements(a1);
  System.out.println(Collections.max(a1));
 }
}

class Point{
 int x, y;
 Point(int x,int y){
  this.x=x;
  this.y=y;
 }
 public String toString(){
  return ("x="+x+","+"y="+y);
 }
}

class Student implements Comparable{
 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);
   if (result==0){
    result=s1.name.compareTo(s2.name);
   }
   return result;
  }
 }
 public int compareTo(Object arg0) {
  Student s=(Student) arg0;
  return num>s.num?1:(num==s.num?0:-1);
 }
 public String toString(){
  return "num:"+num+","+"name:"+name;
 }
}

posted on 2007-02-26 09:08 liaojiyong 阅读(7730) 评论(2)  编辑  收藏 所属分类: Java

评论

# re: java 集合类的排序(转) 2009-07-25 23:43 王五

Collection.sort(List arg0);
博主写错单词了  回复  更多评论   

# re: java 集合类的排序(转)[未登录] 2010-09-12 10:43 java

好  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: