You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中结合枚举类创建HashMap并正确输出关联信息的方法

解决方法

你不需要维护两个HashMap,因为Fruit枚举本身已经包含了name和price信息,直接从枚举实例中获取即可,完全没必要额外存价格到另一个Map里——你的问题根源就是分两次循环打印,把本该在同一行的内容拆成了多行。

步骤1:完善枚举类(添加访问字段的方法)

你的枚举类里name和price是私有字段,需要添加getter方法才能在外部正常访问:

enum Fruit {
    APPLE("APPLE", 20), STRAWBERRY("STRAWBERRY", 70);
    private final int price;
    private final String name;
    
    private Fruit(String name, int price) {
        this.name = name;
        this.price = price;
    }
    
    // 添加getter方法,用于外部获取字段值
    public String getName() {
        return name;
    }
    
    public int getPrice() {
        return price;
    }
}

步骤2:简化主类代码(单Map+单次循环完成输出)

只需要维护一个HashMap<Integer, Fruit>,遍历的时候直接从每个枚举实例中取出name和price,拼接成目标格式:

public static void main(String[] args) {
    HashMap<Integer, Fruit> foodTable = new HashMap<>();
    foodTable.put(1, Fruit.APPLE);
    foodTable.put(2, Fruit.STRAWBERRY);
    
    // 一次循环完成所有输出
    for (Map.Entry<Integer, Fruit> entry : foodTable.entrySet()) {
        int serial = entry.getKey();
        Fruit fruit = entry.getValue();
        // 用printf格式化输出更简洁
        System.out.printf("%d = %s, price = %d%n", serial, fruit.getName(), fruit.getPrice());
    }
}

最终输出

运行后会直接得到你期望的格式:

1 = APPLE, price = 20
2 = STRAWBERRY, price = 70

备选写法(不用printf)

如果习惯字符串拼接,也可以改成下面的写法,效果完全一致:

System.out.println(serial + " = " + fruit.getName() + ", price = " + fruit.getPrice());

内容的提问来源于stack exchange,提问作者Ursula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:35:19