与泛型类类型
问题描述:
类型的返回对象
下面的代码包含一个getter的设置与T类对象:与泛型类类型
public class Cube <T extends State> {
private Set<T> states = new HashSet<>();
public Set<T> getStates() {
return states;
}
}
这似乎给我回状态的设置有效的方式。但是,它会返回一组对象。尝试使用:
Cube<DestinationState> cube = new Cube<>();
Set<DestinationState> set = cube.getStates();
收益率第二行编译错误:
Error:(187, 61) java: incompatible types: java.lang.Object cannot be converted to nl.gijspeters.pubint.graph.state.DestinationState
国家是有多个实现类的通用接口(其中DestinationState)和子。
这可能是一个重复的问题(因为它看起来很基本),但是,我无法找到答案。
答
默认T
替换Object
所以这是基于目标所以尝试这个
Set<DestinationState> set = cube<DestinationState>.getStates();
变化'新立方()的类型推断;'到'新立方();在' –
错字问题,在实际的代码中就是这种情况。修复。 –
刚刚在我的“Playground”项目中试过了你的代码,没有编译错误,尽管 –