gpt4 book ai didi

java - 打印出 3 个 HashMap - Java

转载 作者:行者123 更新时间:2023-12-01 18:18:29 25 4
gpt4 key购买 nike

我目前有此代码;

import java.util.HashMap;

public class Products {
HashMap<Integer, String> id = new HashMap<>();
HashMap<Integer, String> dtion = new HashMap<>();
HashMap<Integer, Double> amount = new HashMap<>();

然后,我通过构造函数将示例数据添加到每个 HashMap 中。我有这三个 HashMap,因为我想打印出 ProductID,以及描述和价格。这意味着 3 个 HashMap 中同一项目的 ProductID 将是相同的。我如何在一行中打印出这些项目?例如,项目 1,这是一个项目,3.20。项目2,这是另一个项目,5.10而不是从第一个 HashMap 中打印出所有内容,然后是第二个 HashMap,然后是第三个 HashMap。

最佳答案

创建一个具有 productIDdescriptionpriceProduct 类会更有意义,并且仅使用单个 HashMap 而不是 3 个。

public class Product
{
private String productID;
private String description;
private double price;

public Product (String productID, String description, double price)
{
this.productID = productID;
this.description = description;
this.price = price;
}

public String toString()
{
return productID + ", " + description + ", " + price;
}
}

public class Products
{
public static void main (String[] args)
{
HashMap<Integer, Product> products = new HashMap<>();
products.put (1, new Product("Item1","This is an item", 3.20));
products.put (2, new Product("Item2","This is another item", 5.10));
...
}
}

关于java - 打印出 3 个 HashMap - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com