我正在尝试让用户输入一个 String
来搜索列表中的值。这很好用,但我还想让 String
具有数字值。这样我就可以得到列表中特定项目的价格。我尝试过:
public List<String, double>
然而这总是给我一个错误。我该怎么存储字符串及其对应的数值?
Map<String, Double> someMap = new HashMap<String, Double>();
Map#put(K, V)
和Map#get(K)
来放置和获取值。Map<String, Double> someMap = new 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();