首页 > 解决方案 > java存储实例变量并使用键值之一进行访问

问题描述

我目前正在uni中学习Java,遇到了这个问题:

public class simpleStockManager {
    private String sku;
    private String name;
    private double price;

    public void newItem(String sku, String name, double price) {
        this.sku = sku;
        this.name = name;
        this.price = price;
    }

    public String getItemName(String sku) {
        return name;
    }
}

我已经声明了一个类和一些实例变量,并尝试使用sku. 因此,如果我按此顺序声明 3 个项目:

simpleStockManager sm = new simpleStockManager();
sm.newItem("1234", "Jam", 3.25);
sm.newItem("5678", "Coffee", 4.37);
sm.newItem("ABCD", "Eggs", 3.98);

当我尝试使用它的getItemName方法时,sku == "5678"它应该返回"Coffee",但它正在返回"Eggs"。我认为这是覆盖前一个项目的最新声明项目,但我不知道如何解决这个问题。任何帮助将不胜感激。

标签: javaclassvariablesconstructor

解决方案


每次调用都会newItem更改实例变量的值。

您将始终获得由m.newItem("ABCD", "Eggs", 3.98);

如果您想使用sku作为键来存储多个变量,您可以使用Map

例如 :

class SimpleStockManager{
    // The key of your map will be sku, 
    //and the name and the price can be for exemple in a Product class
    private HashMap<String, Product>  products = new HashMap<>();

    public void newItem(String sku, String name, double price){
        // A call to newItem will create a new Product and store it 
        products.put(sku, new Product(name, price));
    }

    public String getItemName(String sku){
        if (products.containsKey(sku)){
            return products.get(sku).getName();
        }else {
            return " Product not found...";
        }
    }
}

推荐阅读