stiller_leser
stiller_leser

Reputation: 1572

Java: Stack.pop() + incompatible types

this is the first time I'm working with the Stack-structure. Here's the basic idea: I'm writing a text-based-adventure where the player can visit different rooms. Currently he can't go back. I thought I might use a Stack to document his movements. So if he moves on into a different room I used push() to put the currentCity (Which is an Object of the class City) onto the Stack. It looks like that:

private Stack history;

In the Constructor:

history = new Stack();

In the "go"-function:

history.push(currentCity)

If I try to retrieve the Object in my goBack-function like this:

currentCity = history.pop();
(currentCity is a private variable of the class I'm working in. It's of the type
City)

I thought that would work because the object ontop of my Stack is from the type City and so is the variable currentCity. Still I get incompatible types.

Any help would be greatly appreciated, stiller_leser

Upvotes: 1

Views: 1958

Answers (4)

Bohemian
Bohemian

Reputation: 425278

You are using a raw (untyoed) Stack. Use a typed Stack:

private Stack<City> history;

history = new Stack<City>();

then

currentCity = history.pop();

will compile.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200246

The method is declared as Object pop(), so the compiler only sees Object, which is incompatible with City. If you used Stack<City>, then you'd have the method City pop() and it would work.

BTW Stack is an antiquated class, pre-Collections Framework. You are better off using LinkedList, which has removeLast, acting as pop.

Upvotes: 0

arcy
arcy

Reputation: 13153

You aren't giving nearly enough information for good help. You don't show the declarations of everything, you don't give the exact text of the error message, and this is a case where a small self-contained example would have been quite easy and instructive, even to you.

pop() almost certainly returns Object, and in that case you'll have to cast it to City to overcome the error. But I'm having to guess at several things here...

Upvotes: 0

Perception
Perception

Reputation: 80633

You will either need to cast, or explicitly define your generic parameter for the stack. I recommend specifying the generic parameter.

private Stack<City> history;

history.push(city);
currentCity = history.pop();

Upvotes: 1

Related Questions