Question

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

Était-ce utile?

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

Autres conseils

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...

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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top