java - 将整数映射到对象的最佳方法是什么?以对象为键
问题描述
嘿,这可能是一个愚蠢的问题,但是虽然我可以使用 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 变量。
这是解决这个问题的正确方法吗?如果是这样,我怎么能或有更好的方法。
解决方案
错误:找不到符号
- 你得到这个是因为你在它的范围之外使用了变量MILK。
替代方式
- 您可以为产品制作一个枚举
当前方法的代码
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();
}
}
推荐阅读
- ios - React Native - npx react-native run-ios 在初始化项目后不起作用
- php - 相互使用两个特征的正确方法是什么
- c - 为什么 4/14 在 C 中是 0.00000
- azure - 如何使用保存在 Azure Blob 中的遥测数据来构建报告?
- javascript - 带有 Electron-Vue.js 的串口
- python - df.groupby('MONTH')['TASKTYPE'].value_counts().unstack().loc[month_order].plot.bar(stacked=True) - KeyError
- svelte - 如何在 Svelte 中使用系统信息?
- c# - .net Channels:为什么消费者/读者在无界通道中一个接一个地连续消费生产者输出
- javascript - 将 Firebase Cloudstore 文档同步到 Google 表格时出现问题
- php - 如何根据包含特定字符串的 url 在页面上显示页脚小部件