集合判断比较大小的方法

Comparable与Comparator
1.Comparable
(1)Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。
(2)Comparable接口只有一个方法compare,比较此对象与指定对象的顺序,如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。
2. Comparator
(1)Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现Comparator来新建一个比较器,然后通过这个比较器对类进行排序。
(2)注意:
a.若一个类要实现Comparator接口:它一定要实现compare(T o1, T o2) 函数,但可以不实现 equals(Object obj) 函数。
b.int compare(T o1, T o2) 是“比较o1和o2的大小”。返回“负数”,意味着“o1比o2小”;返回“零”,意味着“o1等于o2”;返回“正数”,意味着“o1大于o2”。

public static void main(String[] args) {
        TreeSet s = new TreeSet();
        s.add(20);
        s.add(34);
        s.add(14);
        s.add(24);
        Iterator iter = s.iterator();
        while(iter.hasNext()){
        System.out.println(iter.next());
        }
        s = new TreeSet();
        s.add(new Student(12,"张三"));
        s.add(new Student(10,"王三"));
        s.add(new Student(14,"赵三"));
        iter = s.iterator();
        while(iter.hasNext()){
            System.out.println(iter.next());
        }
    }

实现一个接口规范来定义比较大小的方法
Comparable:

public class Student implements Comparable {
    private int id;
    private String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Object o) {//o为传进来的对象
        if(o instanceof Student) {//判断o是否是Student的实例,如果不是则抛出异常
            Student s = (Student) o;//因为o是父类的类型,无法访问子类的属性和方法,所以需要强制转换为Student类型
            if(this.id > s.id){//如果自己大于传进来的id则返回1
                return 1;
            }else if(this.id < s.id ){
                return -1;
            }
            return 0;
        }
            throw new RuntimeException("类型不匹配无法比较大小");
    }
}

Comparator:

class Rule implements Comparator{

            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Student && o2 instanceof Student){
                    Student s1 = (Student)o1;
                    Student s2 = (Student)o2;
                    if(s1.getCode() > s2.getCode()) return 1;
                    if(s1.getCode() < s2.getCode()) return -1;
                    return 0;
                }
                throw new RuntimeException("必须是Student类型");
            }
        }

猜你喜欢

转载自blog.csdn.net/weixin_44084434/article/details/91412049