1

So I'm printing an object's name from an arrayList, and it results in printing stuff like "Tacos@5fefccfd". Could you please help me remove this?

I've tried toString() but the problem persists.


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

This code prints "(1)Burger@1d020199 (2)Fries@30eb6038 (3)Tacos@5fefccfd (4)Nuggets@13826e98"

Raj Gupta
  • 35
  • 4
  • You are printing the object class_name@hashcode [toString](https://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode). Check this post [How to override toString() properly in Java?](https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java) – Butiri Dan Sep 02 '19 at 19:56

1 Answers1

1

You are printing the reference of the object. Put something like this in your class, which you save in table.food:

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

If no toString() method is present in your class, then the toString() method of Object will be called. This method does not know the content of your class and by default it just returns the reference.

Charlie
  • 1,169
  • 2
  • 16
  • 31
  • Welcome to Stackoverflow. If I can explain something in more detail please comment. If everything is fine please accept this answer and/or upvote. – Charlie Sep 02 '19 at 20:01
  • Sorry I'm kind of new, what do you mean by save in table.food? – Raj Gupta Sep 02 '19 at 20:05
  • I do not know what the type of table.food is but somewhere you will table.food.add(myFood); and myFood has a Type (class) Burger for example. Maybe Burger also inherits from a Food class then you can put it there and avoid copy & paste it to Fries and Tacos. – Charlie Sep 02 '19 at 20:07