MST

星途 面试题库

面试题:Java中如何在集合框架里对自定义对象进行基于单个属性的比较

假设有一个自定义类Student,包含属性name(String类型)和age(int类型)。现在要将多个Student对象放入TreeSet集合中,使其按照age从小到大排序。请实现相关代码,展示如何通过实现Comparable接口或使用Comparator接口来完成这个功能。
45.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

使用Comparable接口

import java.util.TreeSet;

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Student other) {
        return this.age - other.age;
    }
}

public class Main {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<>();
        studentTreeSet.add(new Student("Alice", 20));
        studentTreeSet.add(new Student("Bob", 18));
        studentTreeSet.add(new Student("Charlie", 22));

        for (Student student : studentTreeSet) {
            System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
        }
    }
}

使用Comparator接口

import java.util.Comparator;
import java.util.TreeSet;

class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getAge() - s2.getAge();
    }
}

public class Main {
    public static void main(String[] args) {
        TreeSet<Student> studentTreeSet = new TreeSet<>(new AgeComparator());
        studentTreeSet.add(new Student("Alice", 20));
        studentTreeSet.add(new Student("Bob", 18));
        studentTreeSet.add(new Student("Charlie", 22));

        for (Student student : studentTreeSet) {
            System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
        }
    }
}