TreeSet自定义比较器实现Comparator接口,覆盖Compare方法

来源:互联网 发布:2016网络大电影市场 编辑:程序博客网 时间:2024/05/18 01:36
import java.util.*;/*TreeSet自定义比较器实现Comparator接口,覆盖Compare方法当元素自身不具备比较性,或者具备的比较性不是所需要的。这是需要让容器自身具备比较性。定义了比较器,将比较器对象作为参数传递给TreeSet的构造函数当两种排序都存在时,以比较器为主定义一个类,实现Comparator接口,覆盖compare方法。以return 0 判断元素是否相同*/class Student implements Comparable//该接口强制让学生具备比较性{    private String name;    private int age;    student(String name,int age)    {        this.name = name;        this.age = age;    }    public int compareTo(Object obj)//覆盖接口里的compareTo方法,用Object 接收参数,不能声明异常    {    if(!(obj instanceof Student))//先判断obj是Student类的实例        throw new RuntimeException("不是学生对象")//抛出运行时异常    Student s = (Student)obj;//强转s    //System.out.println(this.name+"...compareto"+s.name)    if (this.age>s.age)//调用者比较传入参数,        return 1;    if (this.age==s.age)//如果年龄属性相同,再调用名字属性比较    {        return this.name.compareTo(s.name);//调用者 调用String类的comparTo方法 按字典顺序比较 (传入参数)    }           if (this.age<s.age)        return -1;      }    public String getName()    {        return name;    }    public String getAge()    {        return Age;    }   }class  TreeSetDemo2{    public static void main(String[] args)     {        TreeSet ts = new TressSet(new MyCompare());//传进比较器        ts.add(new Student("lisi02",22));        ts.add(new Student("lisi007",20));        ts.add(new Student("lisi09",19));        ts.add(new Student("lisi01",40));        Iterator it = ts.iterator();        while(it.hasNext())        {            System.out.println(it.next());        }    }}class MyCompare implements Comparator//定义比较器{    public int compare(Object o1,Object o2)    {        Student s1 = (Student)o1;        Student s2 = (Student)o2;        int num = s1.get.getName().compareTo(s2.getName());        if(num == 0)        {            new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));            /*            if(s1.getAge()>s2.getAge())                return 1;            if(s1.getAge()==s2.getAge())                return 0;            if(s1.getAge()<s2.getAge())                return -1;            */        }        return num;    }}
0 0
原创粉丝点击