0

So for my local data structure I have the following

DataStructure ds = new DataStructure();
 //Examples to put in the Data Structure "ds"
 ds.menu_item.put("Pizza", new DescItems("A Pizza",2.50,4));
 ds.menu_item.put("Hot Dog", new DescItems("A yummy hot dog",3.50, 3));
 ds.menu_item.put("Corn Dog", new DescItems("A corny dog",3.00));
 ds.menu_item.put("Unknown Dish", new DescItems(3.25));

The DataStructure class has a LinkedHashMap implementation such that

LinkedHashMap<String, DescItems> menu_item = new LinkedHashMap<String, DescItems>();

And finally the DescItems class is

public final String itemDescription;
public final double itemPrice;
public final double itemRating;
public DescItems(String itemDescription, double itemPrice, double itemRating){
 this.itemDescription = itemDescription;
 this.itemPrice = itemPrice;
 this.itemRating = itemRating;
}

There are other constructors to account for no itemDescription and/or itemRating

I'm trying to apply a method to check to see if a value has itemRating other than 0 (0 indicating no rating)

But specifically I came across this problem:

DescItems getC1 = (DescItems)ds.menu_item.get("Pizza");
 System.out.println(getC1.toString());

Only prints out reference information like DescItems@142D091

What should I do to get a specific object variable instead of referencing the object?

asked Dec 13, 2012 at 0:28

3 Answers 3

1

You need to Override the toString() method in DescItems

Something like this:

@Override
public String toString() {
 return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}
answered Dec 13, 2012 at 0:30
0
1

You can override the toString() method in your DescItems class. For example:

public class DescItems {
 . . .
 @Override
 public String toString() {
 // whatever you want here
 return String.format("%1$s (price: $%2$.2f; rating: %3$f)",
 itemDescription, itemPrice, itemRating);
 }
}

The default implementation of toString() returns an object identification string like what you are seeing.

An alternative is to print the exact field(s) you want:

System.out.println(getC1.itemDescription);
answered Dec 13, 2012 at 0:30
0
0

You just need to override the toString() method to return the text that you want.

answered Dec 13, 2012 at 0:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.