java - 使用递归和通用接口(interface)

标签 java generics recursion

我有三个通用接口(interface)(其中两个之间的关系是相反的)并且想用递归方法处理它们:

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>>

最佳答案

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

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());
    }
}

我希望这些更改仍然适合您的设计 - 如果它们不适合您,请告诉我,我会尽力满足您的要求。

呸!艰难的!

关于java - 使用递归和通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088981/

相关文章:

java - 如何为位图设置 onClickListener?安卓java

java - 在带有参数的测试中未找到 JUnit 测试

Java:收据打印机自动切割

java - 构建前 Maven 构建 : Need edit pom. xml

c# - 泛型委托(delegate)不能有逆变返回类型

java - 方法(E[])不适用于参数(int[])

c# - 通用处理程序的集合——这可能吗?

java - 按序遍历突破递归循环

python - 我不懂递归

c# - 遍历C#中的任意字典树结构