这基本上就是我要做的事情:
enum Animal { CAT, FISH }
enum color { RED, GREEN }
int weight = 10
int IQ = 200
AnimalPrice.put((Animal.CAT, Color.GREEN, weight,IQ) , 5)
即。一只重10磅,有200 iq的绿猫的价格是5美元。 有没有办法在java中这样做?我只使用整数列表作为键,但没有使用枚举类型
答案 0 :(得分:4)
我会考虑两种方式:
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;
}
}
我赞成采用第二种方法,因为它更加强大且面向未来。
使用示例:
Map<AnimalPriceKey, Integer> animalPrices = new HashMap<AnimalPriceKey, Integer>();
animalPrices.put(new AnimalPriceKey(Animal.CAT, Color.GREEN, 10, 200), 5);