views:

160

answers:

3

Hi folks,

For my trading program, a Merchant object has a qualities HashMap of enumerated Qualities with Boolean values.

public class Merchants {
   private Map<Qualities, Boolean> qualities = new HashMap<Qualities, Boolean>();

I would like to give each Merchant object a further ratedQualities HashMap of True Qualities with Byte or Integer values representing the Rating of those Qualities.

For example, a given Merchant could have a "1" Rating associated with their True Stockbroking Quality.

The problem is Java does not let me do this easily. The following code demonstrates my intentions but doesn't compile:

private Map<qualities-TRUE, Byte> ratedQualities = new HashMap<qualities-TRUE, Byte>();

According to this link text one solution is to create a Wrapper for the qualities HashMap. Is this the only solution or is there a better way?

Thanks in advance for your help.

+2  A: 

Is there a problem I don't see with just looping over the entries of qualities and adding it to an empty ratedQualities iff the value of the entry in qualities equals true?

That'd be my approach if I understood your question right.

Patrick Bergner
Thanks for your answer. You're right that a loop could do this. However I was hoping there was a simple way to initialise this, as I have numerous similar classes to Merchants with numerous similar attributes stored in HashMaps.
Arvanem
+2  A: 

I suggest to replace the Boolean in the map qualities with an Integer and treat Boolean.FALSE as Integer.valueOf(0).

Aaron Digulla
Thanks for your answer. +1 for suggestion Boolean.FALSE be Integer.valueOf(0).
Arvanem
+6  A: 

Here is an implementation of Merchant using the ideas espoused by Thomas Lötzer and others.

class Merchant
{
    Map<Quality, Integer> ratings = new HashMap<Quality, Integer>();

    boolean hasQuality(Quality quality)
    {
        return ratings.containsKey(quality);
    }

    int getRatingOfQuality(Quality quality)
    {
        Integer rating = ratings.get(quality);
        return (rating != null) ? rating : 0;
    }

    void setRatingOfQuality(Quality quality, int rating)
    {
        ratings.put(quality, rating);
    }
}
Matthew T. Staebler
Thanks for your help. I have upvoted you, Thomas, Eyal, and Aaron, who all deserve credit for this answer.
Arvanem