私が行うことを検討する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);