我有一个通用的 java 类来存储可比对象:
public class MyGenericStorage<T extends Comparable<T>> {
private T value;
public MyGenericStorage(T value) {
this.value = value;
}
//... methods that use T.compareTo()
}
我还有一个名为 Person 的抽象类:
public abstract class Person implements Comparable<Person>
和两个具体的子类,Professor 和 Student:
public class Professor extends Person
public class Student extends Person
现在当我想像这样创建一个 MyGenericStorage 时,我得到一个错误:
//error: type argument Student is not within bounds of type-variable T
MyGenericStorage<Student> studStore = new MyGenericStorage<Student>(new Student());
//this works:
MyGenericStorage<Person> persStore = new MyGenericStorage<Person>(new Student());
我认为这是因为我在理解泛型方面存在根本问题。有人可以向我解释一下这个问题,以及如何解决吗?
编辑:
我已将 MyGenericStorage 更改为以下内容:
public class MyGenericStorage<T extends Comparable<? super T>>
现在它似乎起作用了。谁能解释一下为什么?
最佳答案
您可以使用以下 MyGenericStorage 声明来解决此问题:
class MyGenericStorage<T extends Comparable<? super T>> { …
这意味着T
必须有一个 Comparable
接受一些父类(super class)型的实现 T
.在Student
的情况下和 Professor
,由边界 ( ?
) 表示的父类(super class)型是 Person
.
更新:“现在它似乎可以工作了。有人可以解释为什么吗?”
好吧,我尝试了原来的答案,但让我再试一次。
? super T
意思是“T 的一些父类(super class)型”。假设 T
在这种情况下是学生。因此,Student 必须“为 Student 的某些父类(super class)型”实现 Comparable
Student
延伸Person
, 它实现了 Comparable<Person>
.因此,Student 确实“为 Student 的某些父类(super class)型”实现了 Comparable。
如果您对 Java 泛型有疑问,最好从 Angelika Langer's FAQ. 开始。在这种情况下,the entry about bounded wild-cards可能会有帮助。
关于java - 存储可比较项的通用 java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8315362/