avf*_*avf 5 java generics comparable nested-generics
我有一个存储可比数据的通用java类:
public class MyGenericStorage<T extends Comparable<T>> {
private T value;
public MyGenericStorage(T value) {
this.value = value;
}
//... methods that use T.compareTo()
}
Run Code Online (Sandbox Code Playgroud)
我还有一个名为Person的抽象类:
public abstract class Person implements Comparable<Person>
Run Code Online (Sandbox Code Playgroud)
和两个具体的子类,教授和学生:
public class Professor extends Person
public class Student extends Person
Run Code Online (Sandbox Code Playgroud)
现在当我想像这样创建一个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());
Run Code Online (Sandbox Code Playgroud)
我认为这是因为我对理解泛型存在根本问题.有人可以向我解释这个,还有,如何修复它?
编辑:
我已将MyGenericStorage更改为以下内容:
public class MyGenericStorage<T extends Comparable<? super T>>
Run Code Online (Sandbox Code Playgroud)
现在它似乎工作.有人可以解释原因吗?
您可以使用MyGenericStorage的以下声明来解决此问题:
class MyGenericStorage<T extends Comparable<? super T>> { …
Run Code Online (Sandbox Code Playgroud)
这意味着T必须有一个Comparable接受某些超类型的实现T.在的情况下Student和Professor通过结合所表示的超类型(?)是Person.
更新:"现在似乎有效.有人可以解释原因吗?"
好吧,我尝试了原来的答案,但让我再试一次.
? super T意思是"某些超类型的T".假设T在这种情况下是学生.因此,学生必须实施"可比"学生的某种超类型
Student扩展Person,实现Comparable<Person>.因此,学生确实实现了"对于某些超类学生"的可比性.
如果您对Java Generics有疑问,最好的起点是Angelika Langer的常见问题解答.在这种情况下,关于有界通配符的条目可能会有所帮助.
你的问题是Person扩展Comparable<Person>,所以没关系,但Student扩展了Person,因此它Comparable<Person>不会扩展Comparable<Student>.
在你的约束中你说<T extends Comparable<T>>,因此它们必须是完全相同的类型.衍生类型是不可接受的.