I want to create a Class StacksofStacks, and every stack is made of integers. By now, my code looks like this:
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
}
}
The error occurs when I try to access to the outer class StackOfStacks from the inner class Stack (it is marked as //Error). What I am trying to do is to assign to a Stack called oldStack the topStack of my StackofStacks. In other similar questions I have read that if for example I have an outer class Outer, then I should be able to access to it using:
Outer.this.variable
This works is my outer class is defined as:
class Outer{
//code
}
Now I have something that looks like:
class Outer<T>{
//code
}
Anyway, the error the I get compiling is:
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
The simplest answer would be to get rid of the generics here, because they are not adding anything and are in fact obscuring the problem. The real problem is that Integer
is being used as both a type and a generic type name. I've rewritten your code, replacing the generics with abbreviated forms to better illustrate the issue:
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
}
}
Because you had declared class Stack<Integer>
within the context of the Stack
declaration, Integer
no longer refers to java.lang.Integer
(barring specific circumstances), but the parameterized type.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.