英文:
How do I use Stack.peek to see an instance of an object I pushed into the stack in Java?
问题
抱歉,我只翻译代码部分,以下是翻译好的代码:
import java.util.Stack;
public class Driver {
public static void main(String[] args) {
Stack myStack = new Stack();
Dog dog1 = new Dog("jake");
myStack.push(dog1);
System.out.println(myStack.peek());
}
}
输出结果如下:
Dog@5eb5c224
英文:
Sorry, I just started coding and I'm trying to put an instance of a object into a stack and peek it but when I peek it, I think it's showing me the memory address of the stack item instead of the actual value. The dog class I'm using only one has one variable and it's name.
import java.util.Stack;
public class Driver {
public static void main(String[] args) {
Stack myStack = new Stack();
Dog dog1 = new Dog("jake");
myStack.push(dog1);
System.out.println(myStack.peek());
}
}
This is the output it gives me:
> Dog@5eb5c224
I tried messing with the peek function and trying to place it into another variable of object Dog but I couldn't get anything to work.
答案1
得分: 2
如果在Java中打印一个对象,它会调用该对象的toString
方法来将其转换为字符串。toString
的默认实现是从Object
类继承的,它会打印出类名和对象引用,就像您看到的那样。为了获得有意义的输出,您需要在Dog
类上覆盖toString
方法。请参考例如 https://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java
英文:
if you print an object in java it will call the toString
method on that object to stringify it. The default implementation of toString
is inherited from the Object
class and will print out the class name and its reference as you see it. In order to obtain some meaningful output, you need to override the toString
method on the Dog
class. See for example https://stackoverflow.com/questions/3615721/how-to-use-the-tostring-method-in-java
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论