首页 > 解决方案 > 将整数映射到对象的最佳方法是什么?以对象为键

问题描述

嘿,这可能是一个愚蠢的问题,但是虽然我可以使用 put 函数将对象映射到整数:

product Tuna = new product(1, nutrientsIn);

product Milk = new product(0, nutrientsIn2);

HashMap<product, Integer> productQuantity = new HashMap<product, Integer>();

productQuantity.put(Tuna, 2);

productQuantity.put(Milk, 4);

Diet.totalNutrients(productQuantity);

如果我尝试使用对象的名称作为键来访问值:

System.out.printf("%d\n", productQuantity.get(Milk));

我得到一个错误:找不到符号。我认为这意味着它正在寻找 Milk 变量。

这是解决这个问题的正确方法吗?如果是这样,我怎么能或有更好的方法。

标签: javahashmapkeymapping

解决方案


  1. 错误:找不到符号

    • 你得到这个是因为你在它的范围之外使用了变量MILK
  2. 替代方式

    • 您可以为产品制作一个枚举

当前方法的代码

public class Sample {
    public static void main(String[] args) {
        Product Tuna = new Product(1, "nutrientsIn");

        Product Milk = new Product(0, "nutrientsIn2");

        HashMap<Product, Integer> productQuantity = new HashMap<Product, Integer>();

        productQuantity.put(Tuna, 2);

        productQuantity.put(Milk, 4);

//        Diet.totalNutrients(productQuantity);

        // Use this if in same block
        System.out.printf("%d\n", productQuantity.get(Milk));
        // Use this if in some other block (where getting the error)
        Product makeMilkObject = new Product(0, "nutrientsIn2");
        System.out.printf("%d\n", productQuantity.get(makeMilkObject));
    }
}

class Product{
    int key;
    String nutrient;
    Product(int key, String nutrient){
        this.key = key;
        this.nutrient = nutrient;
    }

    public int getKey() {
        return key;
    }

    public String getNutrient() {
        return nutrient;
    }

    @Override
    public boolean equals(Object obj) {
        return (this.key == ((Product)obj).getKey()) && (this.getNutrient().equals(((Product) obj).getNutrient()));
    }

    @Override
    public int hashCode() {
        return this.getKey();
    }
}

推荐阅读