[英]Return object typed with generic class type
The code below contains a getter to a Set of objects with class T: 下面的代码包含一个带有类T的对象集的getter:
public class Cube <T extends State> {
private Set<T> states = new HashSet<>();
public Set<T> getStates() {
return states;
}
}
Which seemed to me the valid way to return a the Set of states. 在我看来,这是返回一组状态的有效方法。 However, it returns a set of Objects instead.
但是,它会返回一组对象。 Trying to use:
试图使用:
Cube<DestinationState> cube = new Cube<>();
Set<DestinationState> set = cube.getStates();
Yields a compile error on the second line: 在第二行产生编译错误:
Error:(187, 61) java: incompatible types: java.lang.Object cannot be converted to nl.gijspeters.pubint.graph.state.DestinationState
State is a generic interface with multiple implementation classes (among which DestinationState) and subinterfaces. State是具有多个实现类(其中包括DestinationState)和子接口的通用接口。
This may very well be a duplicate question (as it seems quite basic), however, I was not able to find the answer. 这可能是一个重复的问题(因为它看起来很基本),但是,我无法找到答案。
默认情况下, T
替换为Object
因此这是基于目标的类型推断,所以试试这个
Set<DestinationState> set = cube<DestinationState>.getStates();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.