1

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

4

4 回答 4

1

您将需要强制转换或显式定义堆栈的通用参数。我建议指定通用参数。

private Stack<City> history;

history.push(city);
currentCity = history.pop();
于 2013-01-20T13:31:52.313 回答
0

您没有提供足够的信息来获得良好的帮助。您没有显示所有内容的声明,也没有给出错误消息的确切文本,在这种情况下,即使对您来说,一个独立的小型示例也会非常简单和有启发性。

pop() 几乎肯定会返回 Object,在这种情况下,您必须将其强制转换为 City 以克服错误。但我不得不在这里猜测几件事......

于 2013-01-20T13:33:24.833 回答
0

该方法被声明为Object pop(),所以编译器只看到Object,与 不兼容City。如果您使用Stack<City>,那么您将拥有该方法City pop()并且它会起作用。

BTWStack是一个过时的类,pre-Collections Framework。你最好使用LinkedList,removeLast充当pop.

于 2013-01-20T13:34:43.247 回答
0

您正在使用原始(未绑定)堆栈。使用类型化堆栈:

private Stack<City> history;

history = new Stack<City>();

然后

currentCity = history.pop();

将编译。

于 2013-01-20T13:36:39.513 回答