• TreeSet的运用之使用内部比较器实现自定义有序(重要)


    Student.java

    package com.sxt.set3;
    /*
     * TreeSet:有序
     * implements Comparable<Student> 
     * 如果用内部比较器TreeSet必须是实现Comparable接口来实现有序 否则会出现报错:com.sxt.set4.Student cannot be cast to java.lang.Comparable
     * 使用泛型是为了在重写compareTo()方式时,object不用强制转换类型
     */
    //内部比较器:在类内重写比较规则即compareTo()方法
    public class Student implements Comparable<Student> {
        private String name;
        private int age;
        private double salary;
        public Student(String name, int age, double salary) {
            super();
            this.name = name;
            this.age = age;
            this.salary = salary;
        }
        public Student() {
            super();
        }
        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 double getSalary() {
            return salary;
        }
        public void setSalary(double salary) {
            this.salary = salary;
        }
        @Override
        public String toString() {
            return "Student [name=" + name + ", age=" + age + ", salary=" + salary + "]";
        }
        //内部比较器之排序规则 按年龄
        @Override
        public int compareTo(Student o) {
            
            return this.age - o.age;
        }
        
    }

    TestStudent.java

    package com.sxt.set3;
    /*
     * TreeSet
     */
    import java.util.Set;
    import java.util.TreeSet;
    
    public class TestStudent {
        public static void main(String[] args) {
            Set<Student> arr = new TreeSet<>();
            arr.add(new Student("bbb", 21, 532.2));
            arr.add(new Student("ccc", 32, 32.2));
            arr.add(new Student("ddd", 11, 352.2));
            arr.add(new Student("aaa", 15, 32.2));
            //遍历
            for(Student s:arr){
                System.out.println(s);
            }
    //        按照内部比较器按年龄排序结果:
    //        Student [name=ddd, age=11, salary=352.2]
    //        Student [name=aaa, age=15, salary=32.2]
    //        Student [name=bbb, age=21, salary=532.2]
    //        Student [name=ccc, age=32, salary=32.2]
    
        }
    }
  • 相关阅读:
    css表格单元格间距设置
    JavaScript(js)设置输入焦点(focus)
    让div居中的方法
    Window.open()的使用
    getElementsByTagName的用法
    offsetTop获取top值
    js中indexof的使用
    jquery解析json数据
    iframe的使用
    WCF学习笔记Ⅲ
  • 原文地址:https://www.cnblogs.com/qingfengzhuimeng/p/6744293.html
Copyright © 2020-2023  润新知