TreeSet、Set面试,类练习、Employee--Java

实现Comparable接口 按名字排序

@Test
    public void test1() {
        TreeSet set = new TreeSet();
        Employee e1 = new Employee("Chen",new MyDate(1998,01,01));
        Employee e2 = new Employee("Tom",new MyDate(1997,2,01));
        Employee e3 = new Employee("Tim",new MyDate(2002,01,10));
        Employee e4 = new Employee("Jane",new MyDate(2001,2,01));
        Employee e5 = new Employee("Mache",new MyDate(2003,2,01));
        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

Employee类

public class Employee implements Comparable{
    private static LocalDate date = LocalDate.now();
    private String name;
    private int age;
    private MyDate birthday;
    public Employee(String name,MyDate birthday) {
        this.name = name;
        this.birthday = birthday;
        this.age = date.getYear() - birthday.getYear();
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }

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

    @Override
    public int compareTo(Object o) {
        if(o instanceof Employee) {
            int compare =  this.name.compareTo(((Employee) o).getName());
            if(compare!=0) {
                return compare;
            } else {
                return Integer.compare(this.age,((Employee) o).getAge());
            }
        } else {
            throw new RuntimeException("class don't same");
        }
    }
    public MyDate getBirthday() {
        return birthday;
    }
}

实现Comparator接口 按出生日期排序 或者实现Comparable·接口重写compareTo方法

@Test
    public void test2() {
        TreeSet set = new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Employee&&o2 instanceof Employee) {
                    int compareYear = Integer.compare(((Employee) o1).getBirthday().getYear(),((Employee) o2).getBirthday().getYear());
                    if(compareYear !=0) {
                            return -compareYear;
                    } else {
                        int compareMonth = Integer.compare(((Employee) o1).getBirthday().getMonth(),((Employee) o2).getBirthday().getMonth());
                        if(compareMonth != 0) {
                            return -compareMonth;
                        } else {
                            return -Integer.compare(((Employee) o1).getBirthday().getDay(),((Employee) o2).getBirthday().getDay());
                        }
                    }
                } else {
                    throw new RuntimeException("type don't same!");
                }
            }
        });
        Employee e1 = new Employee("Chen",new MyDate(1998,01,01));
        Employee e2 = new Employee("Tom",new MyDate(1997,2,01));
        Employee e3 = new Employee("Tim",new MyDate(2002,01,10));
        Employee e4 = new Employee("Jane",new MyDate(2001,2,01));
        Employee e5 = new Employee("Mache",new MyDate(2003,2,01));
        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);
        Iterator iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

Employee 类

public class Employee{
    private static LocalDate date = LocalDate.now();
    private String name;
    private int age;
    private MyDate birthday;
    public Employee(String name,MyDate birthday) {
        this.name = name;
        this.birthday = birthday;
        this.age = date.getYear() - birthday.getYear();
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }

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

   
    public MyDate getBirthday() {
        return birthday;
    }
}

Set面试题

@Test
    public void test3(){
        HashSet set = new HashSet();
        Person p1 = new Person(1001,"AA");
        Person p2 = new Person(1002,"BB");

        set.add(p1);
        set.add(p2);
        System.out.println(set);

        p1.name = "CC";
        set.remove(p1);
        System.out.println(set);
        set.add(new Person(1001,"CC"));
        System.out.println(set);
        set.add(new Person(1001,"AA"));
        System.out.println(set);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Java中,Set是一种集合数据结构,它不允许重复元素,并且没有固定的顺序。然而,Java中的TreeSet是一种基于红黑树数据结构的Set实现,它可以自定义排序规则。 TreeSet是一个有序的集合,它维护了一个基于元素值的红黑树结构。默认情况下,TreeSet按照元素的自然顺序进行排序。例如,如果元素是整数,则按照从小到大的顺序排列;如果元素是字符串,则按照字典顺序进行排序。 但是,TreeSet也可以使用自定义的Comparator接口实现来指定排序规则。Comparator接口定义了一个compare()方法,它接受两个参数并返回一个int值。如果第一个参数小于第二个参数,则返回负整数;如果第一个参数大于第二个参数,则返回正整数;如果两个参数相等,则返回0。 例如,我们可以创建一个按照字符串长度进行排序的TreeSet,如下所示: ```java TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); treeSet.add("hello"); treeSet.add("world"); treeSet.add("java"); ``` 在这个例子中,我们创建了一个TreeSet并使用了一个自定义的Comparator实现。这个Comparator实现比较两个字符串的长度,并按照长度从小到大的顺序排序。 最终,这个TreeSet中的元素将按照长度从小到大的顺序排列,输出结果为: ``` [java, hello, world] ``` ### 回答2: 在使用Java集合中的TreeSet时,我们默认使用其自然排序规则对元素进行排序。但有时候,我们需要根据自定义的规则对元素进行排序,这时我们可以使用TreeSet提供的自定义排序方法——Comparator。 Comparator是一个接口,其定义了两个方法,分别是compare()和equals()。其中,compare()方法接收两个参数,分别是要比较的对象x和y,这两个对象需要实现Comparator接口;equals()方法用于比较两个对象是否相等。 假设有一个存放Person对象的TreeSet集合,我们需要根据Person的年龄属性进行升序排序,可以通过以下步骤实现: 1. 定义一个Person,包含name和age两个属性,以及相应的getter和setter方法; 2. 在Person实现Comparator接口,并重写compare()方法,在方法中对年龄属性进行比较; 3. 创建一个TreeSet集合,并在构造函数中传入自定义的Comparator对象; 4. 将多个Person对象添加到TreeSet集合中。 具体的代码实现如下: ``` import java.util.*; class Person implements Comparator<Person> { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } @Override public int compare(Person p1, Person p2) { if (p1.getAge() > p2.getAge()) { return 1; } else if (p1.getAge() < p2.getAge()) { return -1; } else { return 0; } } } public class TreeSetDemo { public static void main(String[] args) { TreeSet<Person> set = new TreeSet<Person>(new Person()); set.add(new Person("张三", 28)); set.add(new Person("李四", 20)); set.add(new Person("王五", 25)); for (Person p : set) { System.out.println(p.getName() + " " + p.getAge()); } } } ``` 在代码中,我们定义了一个Person,它实现了Comparator接口,并重写了compare()方法,根据Person对象的age属性进行比较。在主方法中,我们创建了一个TreeSet集合,并在其中添加了多个Person对象,它们会被按照年龄的升序排序。最后,我们通过foreach循环遍历集合中的所有元素,并输出它们的name和age属性。 需要注意的是,在使用自定义比较器时,如果想要保证集合中没有重复元素,我们还需要在Person中重写equals()方法,并根据name和age两个属性进行比较。 ### 回答3: 在使用Java集合中的TreeSet时,数据默认情况下是按照自然顺序进行排序的。但是在某些情况下,我们可能希望按照自己定义的规则进行排序。这时,就需要使用TreeSet的自定义排序规则。 自定义排序规则需要我们实现Comparator接口中的compare方法。该方法用于对实现Comparable接口的对象进行比较。因此,我们需要在自定义实现接口,并重写其中的compare方法。 接下来,我们以Student为例,介绍如何实现TreeSet的自定义排序规则。假设我们希望按照学生的分数进行从高到低的排序。 首先,在Student实现Comparable接口 public class Student implements Comparable<Student>{ private String name; private int score; public Student(String name, int score) { this.name = name; this.score = score; } @Override public int compareTo(Student o) { return o.score - this.score; } } 在该中,我们通过重写compareTo方法,实现了按照学生分数进行排序的规则。 接下来,在使用TreeSet时,我们需要传入一个Comparator对象,该对象用于指定TreeSet中元素的排序规则。示例代码如下: TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getScore() - o1.getScore(); } }); 在该代码中,我们通过匿名的方式实现了Comparator接口,并重写了其中的compare方法。通过该方法,我们指定了从高到低的排序规则。 通过以上的示例代码,我们可以看出,自定义排序规则的具体实现可以根据具体情况进行调整。而在该实现中,我们需要注意以下几点: 1. 实现Comparable接口,用于指定对象的默认排序规则。 2. 实现Comparator接口,在特定情况下自定义排序规则。 3. 在使用TreeSet时,需要传入一个Comparator对象,用于指定排序规则。 以上就是Java集合settreeset之自定义排序规则的详细介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MC6058

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值