使用 Stack.peek 方法来查看我在 Java 中推送到堆栈中的对象实例。

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月6日 13:09:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定