如何在Java中创建关联列表? [英] How to create an associative list in Java?

查看:155
本文介绍了如何在Java中创建关联列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户输入一个字符串来搜索列表中的一个值。这工作正常,但我也希望字符串有一个数值。这样我可以得到列表价格中的某个项目。我试过:

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?

推荐答案

您是否仅存储 String 和一个 Double ,或者您最终需要存储关于每个对象的更多信息?

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

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

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

然后您将能够查询 HashMap for Cheese,您将获得 Product 以及所有的信息它...

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

这篇关于如何在Java中创建关联列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆