n00b programmer
n00b programmer

Reputation: 2701

using tuples with enum types as keys for HashMaps in java

This is basically what I'm trying to do:

enum Animal { CAT, FISH }
enum color { RED, GREEN }
int weight = 10
int IQ = 200
AnimalPrice.put((Animal.CAT, Color.GREEN, weight,IQ) , 5)

i.e. the price of a green cat that weights 10 pounds and has 200 iq is 5 dollars. Is there a way to do this in java? I only got as far as using lists of integer as keys, but nothing about using enum types

Upvotes: 2

Views: 1900

Answers (1)

Liviu T.
Liviu T.

Reputation: 23664

There are 2 ways I would consider doing:

1 create the keys as the string concatanation of those 4 values

String key = Animal.CAT + '_' + Color.GREEN + '_' + weight + '_' + IQ;

2 create an object made up of those values and create a custom equals and hashCode method

public class AnimalPriceKey {
  private Animal animal;
  private Color color;
  private int weight;
  private int iq;

  public AnimalPriceKey(Animal animal, Color color, int weight, int iq) {
    this.animal = animal;
    this.color = color;
    this.weight = weight;
    this.iq = iq;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((animal == null) ? 0 : animal.hashCode());
    result = prime * result + ((color == null) ? 0 : color.hashCode());
    result = prime * result + iq;
    result = prime * result + weight;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    AnimalPriceKey other = (AnimalPriceKey) obj;
    if (animal != other.animal)
      return false;
    if (color != other.color)
      return false;
    if (iq != other.iq)
      return false;
    if (weight != other.weight)
      return false;
    return true;
  }
}

I would favor the second approach as it's much more robust and future proof.

Use example:

Map<AnimalPriceKey, Integer> animalPrices = new HashMap<AnimalPriceKey, Integer>();
animalPrices.put(new AnimalPriceKey(Animal.CAT, Color.GREEN, 10, 200), 5);

Upvotes: 4

Related Questions