Fork me on GitHub

set集合1

特点:1.可以去除重复

          2.存取顺序不一致

          3.没有带索引的方法,所以不能使用普通for循环遍历,也不能通过索引获取或删除元素。

          4.可以将元素按照规则进行排序(想要使用Treeset需要指定排序规则)

自然排序comparable的使用

   1.使用空参构造创建TreeSet集合

   2.自定义Student类实现comparable接口

Student类实现comparable接口

package com.guancun.generic;

public class Student implements Comparable<Student> {
    private String name;
    private  Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

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

    @Override
    public int compareTo(Student o) {
        int result = this.age - o.age;
      result=result==0?this.name.compareTo(o.name):result;
        return result;
    }
}
 private static void comparableTest() {
        TreeSet<Student> treeSet=new TreeSet<>();
        treeSet.add(new Student("zhangsan",12));
        treeSet.add(new Student("xiaoming",12));
        treeSet.add(new Student("lisi",15));
        treeSet.add(new Student("wanwu",13));
        treeSet.add(new Student("wanwu",14));
        for (Student student : treeSet) {
            System.out.println(student);
        }
    }
posted @ 2021-05-07 11:22  风をした  阅读(50)  评论(0)    收藏  举报