MST

星途 面试题库

面试题:Java泛型方法:类型边界与复杂应用

定义一个Java泛型方法,该方法接受两个实现了Comparable接口的泛型类型参数,并返回其中较大的一个。假设你有一个自定义类Student,实现了Comparable接口,比较逻辑是按照学生的成绩(假设Student类有一个int类型的成绩字段)进行比较。在主方法中创建两个Student对象,并调用这个泛型方法,打印出成绩较高的学生。
41.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
class Student implements Comparable<Student> {
    private int score;

    public Student(int score) {
        this.score = score;
    }

    public int getScore() {
        return score;
    }

    @Override
    public int compareTo(Student o) {
        return Integer.compare(this.score, o.score);
    }
}

public class GenericMethodExample {
    public static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) >= 0? a : b;
    }

    public static void main(String[] args) {
        Student student1 = new Student(85);
        Student student2 = new Student(92);
        Student result = max(student1, student2);
        System.out.println("成绩较高的学生成绩: " + result.getScore());
    }
}