Reputation: 844
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?
Upvotes: 0
Views: 112
Reputation: 159754
Currently you are not defining generic types held in your ArrayList
called stack
so you will get a raw Object
return type from ArrayList.get
:
You need to replace
ArrayList stack;
with
ArrayList<Integer> stack;
and similarly
stack = new ArrayList();
with
stack = new ArrayList<Integer>(); // new ArrayList<>(); for Java 7
Also have a look at using java.util.Stack
Upvotes: 3
Reputation: 773
The stack.get(int)
method returns an object. The int here is just the index. If you want to get the value of your stack at index int
and it returns an Integer
you need to do this:
Integer x = stack.get([int index position]);
Upvotes: 1
Reputation: 9821
stack
wasn't informed of what variable type it holds so it resorts to the generic Object
.
ArrayList stack;
should be
ArrayList<Integer> stack;
Upvotes: 1