如何在Java中使用"循环"泛型?

Jea*_*art 3 java generics compiler-errors

编译包含一些泛型的以下代码时出错:

public abstract class State<T extends HasAState<? extends State<T>>>{
    protected T parent;

    public void setParent(){ // It's been simplified for the sake of the question!
        parent.removeState(this); // Error here!
        this.parent = parent;
        parent.addState(this);    // Error here!
    }
}

public interface HasAState<T extends State<? extends HasAState<T>>> {
    public void addState(T state);
    public void removeState(T state);
}
Run Code Online (Sandbox Code Playgroud)

错误是: The method removeState(capture#1-of ? extends State<T>) in the type HasAState<capture#1-of ? extends State<T>> is not applicable for the arguments (State<T>)

实际上我想要的是:class A implements HasAStateclass B extends State<A>哪里B有引用A并且可以调用A.addState(B)(仅因为B扩展State<A>)以及A可以调用的地方B.setParent(this).

我该如何申报课程以便我打算做什么工作?

谢谢

Ral*_*lph 6

我同意Eran Zimmerman的评论.它需要重新考虑你想要的东西.

无论如何,我希望我已经理解了问题,所以我将参数从一个更改为两个,分别描述statehasAState.

public abstract class State<S extends State<S, H>, H extends HasAState<S, H>>{
    protected H parent;

    public void setParent(){ 
        parent.removeState(this);
        this.parent = parent; //!!!this line has no effect!!!
        parent.addState(this);        
    }       
}

public interface HasAState<S extends State<S, H>, H extends HasAState<S, H>> {
    public void addState(State<S, H> state);
    public void removeState(State<S, H> state);
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译!- 注意第二行的警告setParent.