如何在ArrayList中存储然后访问类对象?

时间:2014-11-08 20:41:58

标签: java class object arraylist

所以我有一个名为Product的课程,它存储有关产品的信息,特别是它的名称,价格和数量。它看起来像这样:

import java.util.Scanner;

public class Product {
    private String name;
    private int quantity;
    private double price; 

    public Product(){
        name = "";
        quantity = 0;
        price = 0.0;
    }

    public Product(String name, int prodQuantity, double prodPrice){
        this.name = name;
        quantity = prodQuantity;
        price = prodPrice;
    }

    public void setProductName(String name){
        this.name = name;
    }

    public boolean setProductQuantity(int prodquantity){
        if(prodquantity < 0)
            return false;
        quantity = prodquantity;
            return true;
    }

    public boolean setProductPrice(double prodPrice){
        if(prodPrice < 0.0)
            return false;
        price = prodPrice;
            return true;
    }

    public String getName(){
        return name;
    }

    public int getQuantity(){
        return quantity;
    }

    public double getPrice(){
        return price;
    }

    public void setFromLine(String product){
        StringTokenizer str = new StringTokenizer (product);

        name = str.nextToken();
        String quan = str.nextToken();
        String p = str.nextToken();

        price = Double.parseDouble(p);
        quantity = Integer.parseInt(quan);
    }

}

我想使用setFromLine方法从文件读取一行,看起来像

<product> <price> <quantity>

用空格分隔,并设置给定该行的相应字段,这是应该做的。但是,那么我想将它存储在我的驱动程序中的ArrayList字段中。现在我的驱动程序中有一个方法如下:

public static void readFromFile(String filename) throws IOException {
    File file = new File(filename);//File object opens file
    Scanner inputFile = new Scanner(file);//Scanner object needed to read from file

    balance = inputFile.nextDouble();

    while (inputFile.hasNextLine()) {
        String line = inputFile.nextLine();

        Product proInfo = new Product();
        proInfo.setFromLine(line);

        productInfo.add(proInfo);
    }

    inputFile.close();
}

所以,我的问题是:如果我的代码是正确的,我该如何访问存储在ArrayList中的信息的特定部分。例如,如果我想访问有关价格为15.3且数量为200的产品Lamp的信息,并且它是文件中读取并存储在ArrayList中的第一件事,那么代码行可以我写的是专门得到它的价格或它的具体数量等等。我的驱动程序中的ArrayList字段看起来像这样,顺便说一句:

ArrayList<Product> productInfo = new ArrayList<Product>();

2 个答案:

答案 0 :(得分:2)

如果您不想遍历整个列表,还可以实现equals的{​​{1}}方法,以便按名称比较两个产品。这听起来很复杂但实际上非常有效:)

加入Product班级:

Product

现在将它放入您的Product类后,您可以像这样搜索@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { // the object you are comparing to needs to have the same class (in your case it would be Product return false; // return false if it has not the same class } final Product that = (Product) obj; // now you are sure that it has the same class and you can cast without getting any error return this.name.equalsIgnoreCase(that.name); // if the two names are equal, the products are equal }

ArrayList

详细说明:

您创建要搜索的 Product product = new Product(); product.setName("The Product I am searching for"); if(productInfo.contains(product)){ int index = productInfo.indexOf(product); Product productFromList = productInfo.get(index); } 的新实例并设置其名称。 然后,如果它包含该产品,请检查您的列表(通过调用Product来执行此操作。contains方法将使用您刚刚实现的productInfo.contains(product)方法将列表中的产品与新产品进行比较(并且equals方法按产品名称进行比较)

如果您的名单中有“产品”列表,则可以通过调用equals获取索引。 (此方法实际上使用相同的productInfo.indexOf(product)方法,并且与equals方法完全一样,只是现在它返回元素的索引而不是contains

使用该索引,您可以致电boolean,您将从列表中获取您想知道的所有数据。

修改
这里有一些额外的方法可能会派上用场:

添加新商品

productInfo.get(index)

在列表中添加其他列表

Product car = new Product();   // create the new item
car.setPrice(20000.0);         // set some properties
car.setQuantity(5); 
productInfo.add(car);          // add the item to the list

测试列表是否为空

ArrayList<Product> shipment = new ArrayList<Product>();  // this is another list of items
ArrayList<Product> shipment = new ArrayList<>();   // same as above, only shorter :) you don't need to write <Product> in the new-statement


Product car = new Product();    // create your items like before        
Product toothbrush = new Product(); 

shipment.add(car);             // add all new items to the new list
shipment.add(toothbrush);

productInfo.addAll(shipment);  // add the complete list to your old list

将列表转换为数组

productInfo.isEmpty()    // will return true if the list has NO items at all BUT it does not check for null!

答案 1 :(得分:1)

假设您的ArrayList被命名为productInfo,您必须像这样循环搜索并搜索与您要查询的名称相匹配的产品:

String searchName = "Lamp"; //You would get this as a method parameter or similar
int quantity = 0; //This later holds info about the product

for (Product product : productInfo){
    if (product.getName().equals(searchName)){
        //You can get your info about the specific product here
        quantity = product.getQuantity();
    }
}

但在这种情况下,您最好使用HashMap将值(在您的情况下为产品)分配给密钥(在您的情况下为其名称)。然后,您可以快速访问键的值,如下所示:

Product product = productMap.get("Lamp");