ikarilink
ikarilink

Reputation: 5

Getting object values from a LinkedHashMap

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?

Upvotes: 0

Views: 108

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234847

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

Upvotes: 1

jwismar
jwismar

Reputation: 12268

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

Upvotes: 0

jlordo
jlordo

Reputation: 37833

You need to Override the toString() method in DescItems

Something like this:

@Override
public String toString() {
     return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}

Upvotes: 1

Related Questions