java - 在 Java 中使用具有枚举类型的元组作为 HashMap 的键

标签 java enums hashmap

这基本上就是我想做的事情:

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/

相关文章:

java - 如果一个线程写入一个读取,H2 数据库开始抛出异常

java - 为不同的语言环境定制 java.text 格式化程序

java - 从另一个类访问枚举

swift - 有没有办法让函数接受任何具有 rawValue 字符串的枚举类型?

java - 将两个 HashMap 的值相乘

java - 重铸 'this'解决方法

java - 从 Compute Engine 发布到 Cloud Pub/Sub 主题时的 DEADLINE_EXCEEDED

c++ - 为什么每个常量表达式都可以转换为枚举类型

javascript - 在javascript中使用字符串作为 map 的KEY

java - 并发问题和 hashmap