MST

星途 面试题库

面试题:Java中如何基于TreeMap实现一个按特定属性排序的自定义数据结构

假设有一个自定义类Student,包含姓名(String name)和成绩(int score)两个属性。要求基于Java的TreeMap实现一个数据结构,该结构能按照成绩对Student对象进行升序排列。请描述实现思路并给出关键代码片段。
48.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 定义Student类,实现Comparable接口,在compareTo方法中根据成绩进行比较。
  2. 使用TreeMap来存储Student对象,TreeMap会根据键的自然顺序(这里是Student对象基于成绩的比较顺序)进行排序。

关键代码片段

import java.util.Map;
import java.util.TreeMap;

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 other) {
        return this.score - other.score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

public class StudentTreeMap {
    public static void main(String[] args) {
        Map<Student, Integer> studentMap = new TreeMap<>();
        studentMap.put(new Student("Alice", 85), 1);
        studentMap.put(new Student("Bob", 78), 2);
        studentMap.put(new Student("Charlie", 92), 3);

        for (Map.Entry<Student, Integer> entry : studentMap.entrySet()) {
            Student student = entry.getKey();
            System.out.println("Name: " + student.getName() + ", Score: " + student.getScore());
        }
    }
}