这基本上就是我想做的事情:
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的绿猫的价格是5美元。 有没有办法在java中做到这一点?我只了解使用整数列表作为键,但没有了解使用枚举类型
最佳答案
我会考虑采取两种方法:
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;
}
}
我更喜欢第二种方法,因为它更加强大且面向 future 。
使用示例:
Map<AnimalPriceKey, Integer> animalPrices = new HashMap<AnimalPriceKey, Integer>();
animalPrices.put(new AnimalPriceKey(Animal.CAT, Color.GREEN, 10, 200), 5);
关于java - 在 Java 中使用具有枚举类型的元组作为 HashMap 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917684/