如果有一个泛型类设计为只能包含实现了特定接口的元素,应该使用上界(extends)还是下界(super)?请举例说明如何实现这功能。

在泛型类设计中,如果要求类只能包含实现了特定接口的元素,应该使用 上界(extends)。这是因为上界可以限制泛型类型的范围,确保泛型类型参数必须是指定接口的子类型或实现类,从而满足“只能包含实现了特定接口的元素”的要求。

实现方式

通过使用 extends 关键字,可以限定泛型类型参数为某个接口或类的子类型。以下是具体的实现示例:

示例代码

假设我们有一个接口 ComparableInterface,泛型类 GenericContainer 只能包含实现了该接口的元素。

  1. 定义接口
public interface ComparableInterface {
    int compareTo(ComparableInterface other);
}
  1. 定义实现类 假设有两个类 Person 和 Book,它们实现了 ComparableInterface:
public class Person implements ComparableInterface {
    private String name;
    private int age;

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

    @Override
    public int compareTo(ComparableInterface other) {
        if (other instanceof Person) {
            return Integer.compare(this.age, ((Person) other).age);
        }
        throw new IllegalArgumentException("Cannot compare with non-Person object.");
    }
}

public class Book implements ComparableInterface {
    private String title;
    private String author;

    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    @Override
    public int compareTo(ComparableInterface other) {
        if (other instanceof Book) {
            return this.title.compareTo(((Book) other).title);
        }
        throw new IllegalArgumentException("Cannot compare with non-Book object.");
    }
}
  1. 定义泛型类 使用 extends 限定泛型类型参数 T 必须实现 ComparableInterface:
public class GenericContainer<T extends ComparableInterface> {
    private T element;

    public GenericContainer(T element) {
        this.element = element;
    }

    public void compareWith(T other) {
        System.out.println("Comparison result: " + element.compareTo(other));
    }
}
  1. 使用示例
public class Main {
    public static void main(String[] args) {
        GenericContainer<Person> personContainer = new GenericContainer<>(new Person("Alice", 30));
        personContainer.compareWith(new Person("Bob", 25)); // 输出比较结果

        GenericContainer<Book> bookContainer = new GenericContainer<>(new Book("Java Programming", "John Doe"));
        bookContainer.compareWith(new Book("Python Basics", "Jane Smith")); // 输出比较结果

        // 以下代码会编译错误,因为 String 没有实现 ComparableInterface
        // GenericContainer<String> stringContainer = new GenericContainer<>("Hello");
    }
}

为什么不用下界(super)?

下界(super)主要用于放宽泛型类型的限制,允许泛型类型参数是某个类的父类或其自身。例如,List<? super Integer> 可以接受 Integer、Number 或 Object 类型的列表。这与题目中要求的“只能包含实现了特定接口的元素”是相反的逻辑,因此不适用。

总结

通过上界 extends 可以明确限定泛型类型参数的范围,确保泛型类只能操作实现了特定接口的类型,满足题目要求。