Comparable和Comparator之对象比较

来源:互联网 发布:mysql 指令大全 编辑:程序博客网 时间:2024/06/05 18:53

创建一个实体类:

 

package cn.com.comparator;public class Students {private String name;private int age;public String getName(){return name;}public void setName(String name){this.name = name;}public int getAge(){return age;}public void setAge(int age){this.age = age;}}
Comparator实现对象比较
package cn.com.comparator;import java.util.Comparator;public class StudentComparator implements Comparator{public int compare(Object o1, Object o2){int result=0;if(o1!=null&&o2!=null&&o1 instanceof Students && o2 instanceof Students){Students stu1=(Students)o1;Students stu2=(Students)o2;        result=stu1.getAge()-stu2.getAge();}else{RuntimeException e=new RuntimeException("对象不存在或者不是Students的类型");throw e;}return result;}}Comparable实现对象比较:
package cn.com.comparator;public class StudentComparable implements Comparable{    private String name;    private int age;public String getName(){return name;}public void setName(String name){this.name = name;}public int getAge(){return age;}public void setAge(int age){this.age = age;}public int compareTo(Object o){int result=0;if(o!=null&&o instanceof StudentComparable){StudentComparable student=(StudentComparable)o;result=this.age-student.age;}else{RuntimeException e=new RuntimeException("对象不能为空或者不是StudentComparable类型");throw e;}return result;}}
编写测试类:
package cn.com.comparator;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Random;public class StudentTest{public static void test(){List<Students> stuList=new ArrayList<Students>();//List<StudentComparable> stuList2=new ArrayList<StudentComparable>();Random ran=new Random();for(int i=0;i<10;i++){Students stu=new Students();stu.setName("name:"+i);stu.setAge(ran.nextInt(35));stuList.add(stu);}Comparator stuComparator=new StudentComparator();Collections.sort(stuList,stuComparator);//Collections.reverse(stuList);反转顺序,逆转输出//Comparable stuComparable=new StudentComparable();//Collections.sort(stuList2);for(Students stu:stuList){System.out.println(stu.getName()+": "+stu.getAge());}}public static void main(String[] args){test();}}


原创粉丝点击