[基础回顾-JAVA类集框架篇] 之 集合排序Comparable与Comparator(下)

同样适用于Collection家族类

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

/**
 * 实现比较器类
 * @author foxliucong
 *
 */

public class TheAgeComparator4List implements Comparator{

/**
 * Comparator接口需要是的compare()方法,
 */

 public int compare(Object stu1, Object stu2) {
  if(!(stu1 instanceof Student2)){
   throw new ClassCastException("param type is not Student Class!");
  }
  if(!(stu2 instanceof Student2)){
   throw new ClassCastException("param type is not Student Class!");
  }
  
  return ((Student2)stu1).getAge() - ((Student2)stu2).getAge();
 }
 

//=====================Test==================
   public static void main(String[] args) {
         //同样适用于Collection家族的list
      ArrayList list = new ArrayList();
  
         list.add(new Student2(200903,"fox",25));
         list.add(new Student2(200901,"sherwin",21));
         list.add(new Student2(200902,"oscar",24));
         list.add(new Student2(200904,"angela",22));
     
         /**比较方法就使用Collections中的*/
   Collections.sort(list,new TheAgeComparator4List());
  
      System.out.println("Order by age:");
     
      for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
      }

 }

 


}

 

打印结果:
Order by age:
sno:200901|sname:sherwin|age:21
sno:200904|sname:angela|age:22
sno:200902|sname:oscar|age:24
sno:200903|sname:fox|age:25

你可能感兴趣的:(框架,list,object,Collections,Class,import)