public class Coordinate{
private Integer row;
private Integer column;
public Coordinate(Integer row, Integer column){
this.row = row;
this.column = column;
}
public void setRow(Integer row){
this.row = row;
}
public void setColumn(Integer column){
this.column = column;
}
public Integer getRow(){
return row;
}
public Integer getColumn(){
return column;
}
public String toString(){
return "<" + row.toString() + "," + column.toString() + ">";
}
}好的,我有了这个坐标类,我把它们中的一些推到了一个堆栈上。现在,我想要做的是对其中的一个进行peek(),并能够对我所看到的那个使用getRow和getColumn方法。我该怎么做呢?我遇到的问题是,我创建了一个新的坐标实例,然后将stack.peek()赋值给它,然后使用它上的方法,但这不起作用。迷惑
发布于 2012-04-10 07:43:43
Coordinate c = new Coordinate(1,2);
Stack<Coordinate> s = new Stack<Coordinate>();
s.push(c);
System.out.println(s.peek());
Coordinate c2 = (Coordinate)s.pop();
System.out.println(c2);
System.out.println(c2.getRow());不过,这里有个提示,不要使用java.util.Stack。它来自原始的收藏库,这不是很好。
修改编辑以表示类型转换,这听起来就是您在本例中所需要的。注c和c2将指向同一个对象。
发布于 2012-04-10 08:04:09
看起来您可能需要将stack.peek()的结果强制转换为您的Coordinate类。像System.out.println(((Coordinate)mazeStack.peek()).getRow());这样的东西可能就是你要找的。
https://stackoverflow.com/questions/10081233
复制相似问题