2

これは基本的に私がやろうとしていることです:

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

つまり、体重が 10 ポンドで IQ が 200 の緑色の猫の価格は 5 ドルです。Javaでこれを行う方法はありますか? 整数のリストをキーとして使用することしかできませんでしたが、列挙型の使用については何もしませんでした

4

1 に答える 1

4

私が行うことを検討する2つの方法があります:

1 これらの 4 つの値の文字列連結としてキーを作成します

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

2 これらの値で構成されるオブジェクトを作成し、カスタム equals および hashCode メソッドを作成します

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

2 番目のアプローチの方がはるかに堅牢で将来性があるため、私は 2 番目のアプローチを好みます。

使用例:

Map<AnimalPriceKey, Integer> animalPrices = new HashMap<AnimalPriceKey, Integer>();
animalPrices.put(new AnimalPriceKey(Animal.CAT, Color.GREEN, 10, 200), 5);
于 2012-08-11T21:17:45.847 に答える