How to create an associative list in Java?

非 Y 不嫁゛ 提交于 2020-02-24 09:07:15

问题


I am trying to have a user enter a String to search for a value in a list. This works fine, but I also want the String to have a numeric value. This way I can get the certain item in the lists price. I tried:

public List<String, double>

However this always gives me an error. How can I store strings and their corresponding numeric value?


回答1:


Are you only storing a String and a Double, or will you eventually need to store more information about each object?

For example, you're talking about storing a name and a price. If this is for a shopping-like program, you would probably be best to store all the information for each product in a new class, and then store the class in the HashMap. For example..

// 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);

You will then be able to query the HashMap for "Cheese" and you'll get the Product and and all the information for it...

Product cheese = products.get("Cheese");
double price = cheese.getPrice();



回答2:


Use a Map.

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

Then, you can use Map#put(K, V) and Map#get(K) to put and get values.

Check out the Map documentation as well.

From Java 7 onwards, you can omit the generic type within the constructor's declaration:

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


来源:https://stackoverflow.com/questions/10966855/how-to-create-an-associative-list-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!