import java.util.ArrayList;
class Stack {
private ArrayList stack;
private int pos;
Stack() {
stack = new ArrayList();
pos = -1;
}
int pop() {
if(pos < 0) {
System.out.println("Stack underflow.");
return 0;
}
int out = stack.get(pos);
stack.remove(pos);
pos--;
return out;
}
}
I am trying to write a basic variable length stack and this is a snippet of my code. When I run this, I get an error:
Main.java:16: error: incompatible types
int out = stack.get(pos);
^
required: int
found: Object
Why is this being passed as an object?
Currently you are not defining generic types held in your
ArrayListcalledstackso you will get a rawObjectreturn type fromArrayList.get:You need to replace
with
and similarly
with
Also have a look at using
java.util.Stack