我正在尝试让用户输入String来搜索列表中的值。这工作正常,但我也希望String具有数字值。这样,我就可以在标价中获得某些商品。我试过了:

public List<String, double>

但是,这总是给我一个错误。如何存储字符串及其相应的数值?

最佳答案

您仅存储StringDouble,还是最终需要存储有关每个对象的更多信息?

例如,您正在谈论存储名称和价格。如果这是用于购物类程序,则最好将每个产品的所有信息存储在一个新类中,然后将该类存储在HashMap中。例如..

// Class for your product and all related information...
public class Product {
    String name;
    double price;
    String color;
    double weight;

    public Product(String name, double price, String color, double weight){
        this.name = name;
        this.price = price;
        this.color = color;
        this.weight = weight;
    }
}

// Now add each Product to a HashMap (in your main class)...
HashMap<String,Product> products = new HashMap<String,Product>();
products.put("Cheese", new Product("Cheese",1.10,"Yellow",0.5);
products.put("Milk", new Product("Milk",2.0,"White",1.5);

然后,您将能够在HashMap中查询"Cheese",并且您将获得Product及其所有信息...
Product cheese = products.get("Cheese");
double price = cheese.getPrice();

09-11 18:16
查看更多