java - 从内部类 StackofStacks<T> 访问外部类

标签 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 的堆栈。在其他类似的问题中,我读到,如果例如我有一个外部类 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

最佳答案

最简单的答案是去掉这里的泛型,因为它们没有添加任何东西,实际上掩盖了问题。真正的问题是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 (除非特殊情况),但是参数化类型。

关于java - 从内部类 StackofStacks<T> 访问外部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51105441/

相关文章:

actionscript-3 - 如何在 ActionScript 3 中正确测试类继承?

pointers - 使用链表实现的 Stack ADT 的时间复杂度

java - 使用 spring-data-mongodb 进行审计

java - 这个奇怪的泽西警告是什么意思?

java - 如何使用mapstruct或modelmapper从一个对象递归更新另一个对象的嵌套对象?

java - 未知对象的调用方法

java - 使用 chromedriver 2.20 和 selenium server 2.48.2,测试失败并出现错误 "Chrome failed to start: exited abnormally"

c++ - 不断收到错误 "is not a class or namespace"或 "cannot call member function without object"

r - 循环堆叠栅格

language-agnostic - 有什么方法可以显示函数调用图吗?