【问题标题】:How do I prevent hashcode from printing when I print an object using the .get() method in an arrayList? [duplicate]当我在 arrayList 中使用 .get() 方法打印对象时,如何防止打印哈希码? [复制]
【发布时间】:2019-09-02 19:46:09
【问题描述】:

所以我从 arrayList 打印一个对象的名称,它会打印出像“Tacos@5fefccfd”这样的东西。你能帮我删除这个吗?

我已尝试toString(),但问题仍然存在。


System.out.println("Customer#" + orderNum + ": " + table.food.get(choice).toString());

System.out.println("");
for (int j = 0; j < table.food.size(); j++) 
{
     System.out.print("(" + (j+1) + ")" + table.food.get(j) + " ");
}
System.out.println("");

此代码打印“(1)Burger@1d020199 (2)Fries@30eb6038 (3)Tacos@5fefccfd (4)Nuggets@13826e98”

【问题讨论】:

标签: java string arraylist


【解决方案1】:

您正在打印对象的引用。在你的课堂上放一些这样的东西,你保存在 table.food 中:

public String toString() { 
    return this.name;
} 

如果您的类中不存在 toString() 方法,则将调用 Object 的 toString() 方法。此方法不知道您的类的内容,默认情况下它只返回引用。

【讨论】:

  • 欢迎来到 Stackoverflow。如果我可以更详细地解释一些事情,请发表评论。如果一切正常,请接受此答案和/或投票。
  • 对不起,我是个新手,你说的保存在 table.food 中是什么意思?
  • 我不知道 table.food 的类型是什么,但你会在某个地方 table.food.add(myFood);例如, myFood 有一个 Type (class) Burger。也许 Burger 也继承自 Food 类,然后您可以将其放在那里,避免将其复制粘贴到 Fries 和 Tacos。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 2016-12-19
  • 2010-09-09
  • 2012-10-23
  • 1970-01-01
  • 2022-12-10
相关资源
最近更新 更多