使用递归和通用接口

时间:2011-08-17 06:58:18

标签: java generics recursion

我有三个通用接口(其中两个之间存在反转关系),并希望以递归方式处理它们:

public interface User<R extends Role<R,U>, U extends User<R,U>>
{
  public R getRole();
  public void setRole(R role);
}

public interface Role<R extends Role<R,U>,U extends User<R,U>>
{
  public List<R> getRoles();
  public void setRoles(List<R> roles);

  public List<U> getUser() ;
  public void setUser(List<U> user);
}

现在我想在我的Worker类中使用递归进行一些处理:

public <R extends Role<R,U>,U extends User<R,U>> void recursion(List<R> roles)
{
  for(R role : roles)
  {
    recursion(role.getRoles());
  }
}

我收到此错误,但我并未弄清楚为什么这不起作用或我如何解决这个问题:

Bound mismatch: The generic method recursion(List<R>) of type Worker is not
applicable for the arguments (List<R>). The inferred type User<R,User<R,U>>
is not a valid substitute for the bounded parameter <U extends User<R,U>>

2 个答案:

答案 0 :(得分:2)

我修改了它,没有使用通用通配符?,所以它编译 在删除与问题无关的方法声明后:

public interface Role<R extends Role<R, U>, U extends User<R, U>> {
    public List<Role<R, U>> getRoles(); // Change here to return type
}

public interface User<R extends Role<R, U>, U extends User<R, U>> { // No change
}

// Change to method parameter type
public static <R extends Role<R, U>, U extends User<R, U>> void recursion(List<Role<R, U>> roles) {
    for (Role<R, U> role : roles) { // Change to element type
        recursion(role.getRoles());
    }
}

我希望这些更改仍然适合您的设计 - 如果它们不适合您,请告诉我,我会尝试解决您的要求。

唷!艰难的一个!

答案 1 :(得分:2)

您已经注意到需要在其中一个参数中指定类型U。你可以这样做,或者如果你想忽略U类型,你可以使用?代替:

public <R extends Role<R,?>> void recursion(List<R> roles)
{
  for(R role : roles)
  {
    recursion(role.getRoles());
  }
}
相关问题