返回一个接口集合

apo*_*020 1 java generics

我创建了以下界面

public interface ISolutionSpace {
  public boolean isFeasible();
  public boolean isSolution();
  public Set<ISolutionSpace> generateChildren();
}
Run Code Online (Sandbox Code Playgroud)

但是,在ISolutionSpace一个名为的类的实现中EightQueenSolutionSpace,我将返回一组EightQueenSolutionSpace实例,如下面的存根:

@Override
public Set<ISolutionSpace> generateChildren() {
  return new HashSet<EightQueenSolutionSpace>();
}
Run Code Online (Sandbox Code Playgroud)

但是这个存根不会编译.我需要做出哪些改变?

编辑:我也试过'HashSet',并尝试使用extends关键字.但是,由于'ISolutionSpace'是一个接口,并且EightQueenSolutionSpace是'ISolutionSpace' 的实现(而不是子类),它仍然无法正常工作.

Axe*_*ine 9

两种可能性:

@Override
public Set<? extends ISolutionSpace> generateChildren() {
  return new HashSet<EightQueenSolutionSpace>();
}
Run Code Online (Sandbox Code Playgroud)

要么

@Override
public Set<ISolutionSpace> generateChildren() {
  return new HashSet<ISolutionSpace>();
}
Run Code Online (Sandbox Code Playgroud)

并简单地将EightQueenSolutionSpace的实例添加到集合中.

  • ?extends X是泛型的有界通配符.X只是通配符的上限,即使关键字是extends,它也可以是接口或类. (2认同)