返回使用泛型类类型键入的对象

时间:2016-11-21 11:10:27

标签: java generics

下面的代码包含一个带有类T的对象的getter:

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

State是具有多个实现类(其中包括DestinationState)和子接口的通用接口。

这可能是一个重复的问题(因为它看起来很基本),但是,我无法找到答案。

1 个答案:

答案 0 :(得分:1)

默认情况下T已替换为Object,因此这是基于目标的类型推断,请尝试此操作

Set<DestinationState> set = cube<DestinationState>.getStates();