Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java中创建关联列表?_Java_List_Hashmap - Fatal编程技术网

如何在Java中创建关联列表?

如何在Java中创建关联列表?,java,list,hashmap,Java,List,Hashmap,我正在尝试让用户输入字符串,以在列表中搜索值。这很好,但是我还希望字符串有一个数值。这样我就可以得到价目表上的某些商品。我试过: public List<String, double> 公共列表 然而,这总是给我一个错误。如何存储字符串及其对应的数值?使用映射 Map<String, Double> someMap = new HashMap<String, Double>(); 您是只存储字符串和双精度,还是最终需要存储关于每个对象的更多信息 例如,您

我正在尝试让用户输入
字符串
,以在列表中搜索值。这很好,但是我还希望
字符串
有一个数值。这样我就可以得到价目表上的某些商品。我试过:

public List<String, double>
公共列表
然而,这总是给我一个错误。如何存储字符串及其对应的数值?

使用映射

Map<String, Double> someMap = new HashMap<String, Double>();

您是只存储
字符串
双精度
,还是最终需要存储关于每个对象的更多信息

例如,您正在谈论存储名称和价格。如果这是一个类似购物的程序,那么最好将每个产品的所有信息存储在一个新类中,然后将该类存储在
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);

Map#get(k)只接受一个参数。i、 e钥匙。哦,这更好。谢谢
// 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);
Product cheese = products.get("Cheese");
double price = cheese.getPrice();