随笔 - 24  文章 - 0  trackbacks - 0
<2011年1月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345

常用链接

留言簿

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

//学生类
package l6;

import java.util.Comparator;

public class Student implements Comparable {

 public int num;
 public String name;
 

 public Student(int num, String name) {
  this.num = num;
  this.name = name;
 }

 public int compareTo(Object o) {
  Student s = (Student) o;
  if (num > s.num) {
   return 1;
  } else if (num == s.num) {
   return 0;
  } else {
   return -1;
  }
 }

 public String toString() {
  return "num:" + num + " name:" + name;
 }

 public int compare(Object o1, Object o2) {
  // TODO Auto-generated method stub
  return 0;
 }
}

//学生比较器

package l6;

import java.util.Comparator;

public  class StudentComparator implements Comparator {

 public int compare(Object o1, Object o2) {
  Student s1 = (Student) o1;
  Student s2 = (Student) o2;
  if (s1.num > s2.num) {
   return 1;
  } else if (s1.num < s2.num) {
   return -1;
  } else {
   return s1.name.compareTo(s2.name);
  }
 }
}


//测试类
package l6;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

public class ArrayListTest {

 /**
  * @param args
  */

 public static void main(String[] args) {

  ArrayList<Student> slist = new ArrayList<Student>();
  Student s1 = new Student(1, "z1");
  slist.add(s1);
  Student s3 = new Student(2, "z3");
  slist.add(s3);
  Student s2 = new Student(2, "z2");
  slist.add(s2);
  Student s5 = new Student(2, "z5");
  slist.add(s5);
  Student s4 = new Student(4, "z4");
  slist.add(s4);

   // Collections.sort(slist); //未使用比较器
    Collections.sort(slist, new StudentComparator());//未使用比较器
  PaintE(slist);

 }

 public static void PaintE(Collection c) {
  Iterator it = c.iterator();
  while(it.hasNext()){
   System.out.println(it.next().toString());
  }
  

 }

}


 

 

posted on 2011-01-12 23:01 冯占科 阅读(212) 评论(0)  编辑  收藏

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


网站导航: