John Smith
John Smith

Reputation: 9

stack.peek() method- Java

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() + ">";
}
}

ok so i have this coordinate class and i have some of them pushed onto a stack. now what i want to do is peek() at one of them and be able to use the getRow and getColumn method at the one i peek at. How do i do this? The problem i am having is i am creating a new instance of Coordinate and then assigning stack.peek() to it and then using the methods on it but that not working. Confused

Upvotes: 0

Views: 1454

Answers (2)

BillRobertson42
BillRobertson42

Reputation: 12883

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

Here's a tip though, don't use java.util.Stack. Its from the original collections library which wasn't very good.

edit modified to represent the cast, which is what it sounds like you need in this case. Note c and c2 will point to the same object.

Upvotes: 1

Tom
Tom

Reputation: 3166

It looks like you might have to cast the result of stack.peek() to your Coordinate class. Something like System.out.println(((Coordinate)mazeStack.peek()).getRow()); might be what you are looking for.

Upvotes: 1

Related Questions