Search code examples
javastackincompatibletypeerror

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


Solution

  • 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();