从内部类StackofStacks <t>访问外部类

时间:2018-06-29 15:51:36

标签: java class stack this

我想创建一个StacksofStacks类,每个堆栈都由整数组成。现在,我的代码如下:

class StacksOfStacks<Stack>{
  Stack<Integer> topStack;
  Stack<Integer> nextStack;
  public StacksOfStacks(){
    topStack = null;
  }
  public StacksOfStacks(Stack<Integer> topStack){
    this.topStack = topStack;
  }
  public class Stack<Integer>{
    int size;
    int maxSize;
    int top;
    public Stack(int top, int maxSize){
      this.top = top;
      this.size = 1;
      this.maxSize = maxSize;
    }
    public void push(int data){
      if(size == maxSize){
        Stack<Integer> newStack = new Stack<Integer>(data, maxSize); //Create new stack
        Stack<Integer> oldStack = StacksOfStacks.this.topStack; //Error
        // some code
      }
      //some code
    }
  }

当我尝试从内部类Stack访问外部类StackOfStacks时发生错误(标记为// Error)。我想做的就是将我的StackofStacks的topStack分配给一个叫做oldStack的Stack。在其他类似的问题中,我读到例如,如果我有一个外部类Outer,那么我应该可以使用以下方法访问它:

Outer.this.variable

此作品是我的外部类定义为:

class Outer{
//code
}

现在我看起来像:

class Outer<T>{
//code
}

无论如何,我编译的错误是:

StacksOfStacks.java:22: error: incompatible types: StacksOfStacks<Stack>.Stack<java.lang.Integer> cannot be converted to StacksOfStacks<Stack>.Stack<Integer>
        Stack<Integer> oldStack = StacksOfStacks.this.topStack; //Error
                                                     ^
  where Stack,Integer are type-variables:
    Stack extends Object declared in class StacksOfStacks
    Integer extends Object declared in class StacksOfStacks.Stack
1 error

1 个答案:

答案 0 :(得分:2)

最简单的答案是在这里摆脱泛型,因为它们没有添加任何东西,并且实际上掩盖了问题。真正的问题是Integer既被用作类型名称又被用作泛型类型名称。我已经重写了您的代码,用缩写形式替换了泛型以更好地说明问题:

class StacksOfStacks<S>{
  Stack<Integer> topStack;
  Stack<Integer> nextStack;
  public StacksOfStacks(){
    topStack = null;
  }
  public StacksOfStacks(Stack<Integer> topStack){
    this.topStack = topStack;
  }
  public class Stack<I>{
    int size;
    int maxSize;
    int top;
    public Stack(int top, int maxSize){
      this.top = top;
      this.size = 1;
      this.maxSize = maxSize;
    }
    public void push(int data){
      if(size == maxSize){
        Stack<I> newStack = new Stack<I>(data, maxSize); //Create new stack
        Stack<I> oldStack = StacksOfStacks.this.topStack; //Error
        // some code
      }
      //some code
    }
  }

因为您已经在class Stack<Integer>声明的上下文中声明了Stack,所以Integer不再引用java.lang.Integer(除非有特殊情况),而是参数化类型。 / p>