这是我第一次使用堆栈结构。基本想法如下:我正在编写一个基于文本的冒险游戏,玩家可以访问不同的房间。目前他还不能回去。我想我可以使用堆栈来记录他的 Action 。因此,如果他移动到另一个房间,我使用 push() 将 currentCity (这是 City 类的对象)放入堆栈中。看起来像这样:
private Stack history;
在构造函数中:
history = new Stack();
在“go”函数中:
history.push(currentCity)
如果我尝试像这样在 goBack 函数中检索对象:
currentCity = history.pop();
(currentCity is a private variable of the class I'm working in. It's of the type
City)
我认为这会起作用,因为我的 Stack 顶部的对象来自 City 类型,变量 currentCity 也是如此。我仍然得到不兼容的类型。
任何帮助将不胜感激, 斯蒂勒_莱瑟
最佳答案
您需要强制转换或显式定义堆栈的通用参数。我建议指定通用参数。
private Stack<City> history;
history.push(city);
currentCity = history.pop();
关于Java:Stack.pop() + 不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425008/