【问题标题】:Whats the best way to map an integer to an object.with the object as a key将整数映射到对象的最佳方法是什么?以对象为键
【发布时间】:2020-03-02 04:00:43
【问题描述】:

嘿,这可能是一个愚蠢的问题,但我可以使用 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 变量。

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

【问题讨论】:

  • 你在Product类中实现了equals吗?
  • 我没有。我现在试过了,但是找不到。你能进一步解释一下你的意思吗?
  • 一般在 Java 中,对象 strt 以小写字母 (tuna) 和类以大写字母 (Tuna) 开头。

标签: java hashmap key mapping


【解决方案1】:
  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();
    }
}

【讨论】:

  • 我可能会误解,但我试图使用产品对象作为地图中的键,值是整数。我宁愿不将数量变量存储为类变量。
  • @ras64 好的..所以我正在编辑我的答案。我忽略了这一点。我以为您将 productKeyArgument 存储为地图上的值。
  • @ras64 你也可以使用枚举,为此
  • 是的,当值来自我用作键的类时,我能够做到这一点。但是我不确定是否可以将单独的原语作为值。如果是这样,您能否推荐任何其他实现类似结果的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2016-12-26
相关资源
最近更新 更多