美文网首页
day15-04-集合框架(实现Comparator方式排序)

day15-04-集合框架(实现Comparator方式排序)

作者: 姗婷 | 来源:发表于2020-06-22 19:24 被阅读0次

TreeSet的第二种排序方式。
大概元素自身不具备比较性,或者具备的比较性不是所需要的。
这时就需要让集合自身具备比较性。
在集合初始化是,就有了比较方式。---构造函数。

当元素自身不具备比较性,或者具备的比较性不是所需要的。
这时需要让容器自身具备比较性。
定义了比较器(Comparator),将比较器作为参数传递给TreeSet集合的构造函数

当两种方式都存在时,以比较器(Comparator)为主,比较器比较常用。
定义一个类,实现Comparator接口,覆盖compare方法。
comparable是compareTo方法。

两种方式原理都是二叉树。都是以return 0.元素是否相同

import java.util.*;
class Student implements Comparable//该接口强制让学生具备比较性
{
    private String name;
    private int age;
    Student(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    //复写compareTo方法
    public int compareTo(Object obj)
    {

        if(!(obj instanceof Student))
            throw new RuntimeException("不是学生对象");
        Student s = (Student)obj;

        //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);
         return -1;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return age;
    }
}
class  TreeSetDemo2
{
    public static void main(String[] args) 
    {
        //传一个的Comparator接口的子类对象
        TreeSet ts = new TreeSet(new MyCompare());
        ts.add(new Student("lisi02",22));
        ts.add(new Student("lisi007",20));
        ts.add(new Student("lisi09",19));
        ts.add(new Student("lisi08",18));
        ts.add(new Student("lisi007",29));
        //ts.add(new Student("lisi01",40));

        Iterator it =  ts.iterator();
        while(it.hasNext())
        {
            Student stu = (Student)it.next();
            System.out.println(stu.getName()+"...."+stu.getAge());
        }
    }
}


class MyCompare implements Comparator
{
    //已经具备equals方法,不用覆盖,要覆盖Compare
    public int compare(Object o1,Object o2)
    {
        //比较学生,强转
        Student s1  = (Student)o1;
        Student s2  = (Student)o2;
        //比较字符串compareTo方法,判断主要条件
        int num =s1.getName().compareTo(s2.getName());
        //当主要条件姓名相同(num==0)时 ,判断次要条件
        if(num==0)
        {
            //Integer也具备比较自然顺序compareTo方法

            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
        }
        /*if(num==0)
        {
            if(s1.getAge()>s2.getAge())
                return 1;
            if(s1.getAge()=s2.getAge())
                return 0;
            if(s1.getAge()=s2.getAge())
                return -1;
        }
        */
            return num;
    }
}

相关文章

网友评论

      本文标题:day15-04-集合框架(实现Comparator方式排序)

      本文链接:https://www.haomeiwen.com/subject/wryvxktx.html