Reputation: 189
Im doing a little text adventure. Im current working on a inventory. I tried to do my inventory with a list:
ArrayList<Object> inventar = new ArrayList<Object>();
I initialize Objects as Items:
Item holzschwert = new Item("Holzschwert", 1, 5);
inv.addToInventar(holzschwert);
Here's my add Method:
public void addToInventar(Object ...item){
inventar.add(item);
}
But everytime i want to print out my inventory (here's my toString() function) i still get the Hash code:
@Override
public String toString() {
return "Inventar [ Inventar = " + inventar + " ]";
}
and my print method
Object test = inv.getInventar();
String ausgabe = inv.toString();
System.out.println(ausgabe);
and the console log:
Inventar [ Inventar = [[Ljava.lang.Object;@281c35ec] ]
Thank you for your help :)
Upvotes: 1
Views: 135
Reputation: 37655
The mistake is
public void addToInventar(Object ...item){
inventar.add(item);
}
Here item
is an Object[]
, because you used varargs (...
). What you are seeing is the result of calling toString
on an array.
You want
public void addToInventar(Object item){
inventar.add(item);
}
or possibly
public void addToInventar(Object... items){
for (Object item : items)
inventar.add(item);
}
EDIT
In addition to this answer, I should point out that you should probably not be using List<Object>
anyway. List<Item>
would be better as mistakes like this are more likely to be spotted by the compiler. The signature addToInventar(Object... items)
should really be avoided like the plague, as it will accept literally any sequence of arguments of any length. All reference types are Object
s and all primitives can be autoboxed.
Upvotes: 3
Reputation: 166
If you do not care about the exact format of the output, you can do something like this in your Item
class:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
ToStringBuilder
is part of the Apache Commons Lang library. If you want it specifically formatted a certain way, then go with @Code Whisperer and write your own implementation.
Upvotes: 0
Reputation: 1041
@Override
public String toString() {
StringBuffer stuff = new StringBuffer();
for (Object item : inventar) {
stuff.append(item.getName()); // you need a getter for the item name
stuff.append(" ");
}
return stuff.toString();
}
Both your inventory and items are Objects. If you just print the objects and not the fields you will only get their memory address as output:
Ljava.lang.Object;@281c35ec
not the properties you've set up for them.
Upvotes: 0
Reputation: 5982
Override the Item class toString() method.
class Item{
@override
public String toString(){
//Give your implementation
}
}
Upvotes: 0