2014-11-08 77 views
1

所以我有这个类叫Product存储有关产品的信息,特别是它的名称,它的价格和数量。它看起来像这样:如何存储并访问ArrayList中的类对象?

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,并且它是第一个读入文件并存储在ArrayList中的产品,那么我可以编写哪些代码行来明确价格或它的数量而言,等我ArrayList在我的驱动程序领域是这样的,顺便说一句:

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

'productInfo.get(0).getPrice()',以获得第一元件的价格。 – msfoster 2014-11-08 20:45:37

+0

我不知道你的货币计算有多少准确度,但是如果你想要精度,'double'是不是... – fge 2014-11-08 20:48:53

回答

2

如果你不想通过整个列表进行迭代,你也可以实现你Productequals方法,这样会比较两个产品由它的名字。这听起来很复杂,但它实际上是相当有效:)

把你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的新实例,您正在搜索并设置其nam即 然后你检查你的清单,如果它包含那个产品(你通过调用productInfo.contains(product)来做到这一点,contains方法会使用上面刚刚实现的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! 

转动列表到一个数组

Product[] array = new Product[productInfo.size()]; // create an array of the same size as your list 
productInfo.toArray(array); // pass the array to this method and afterwards it will be filled with all the products of your list. 
+0

这不一定是我正在寻找一个产品,它是信息。如果我的readFromFile方法的话,它应该只存储数组索引0的所有第一个产品信息,将所有第二个产品信息存储在索引1处,所有第三个产品信息存储在索引2处,然后我需要知道如何访问和操作这些信息。所以,如果我需要更改第二个产品的价格,我该如何得到它。我相信,让我感到沮丧的是在其他对象(ArrayList对象)内存储对象(在本例中为Product对象)的想法。 – user3525572 2014-11-08 21:23:02

+0

@ user3525572我明白了,如果你知道你的产品在哪个索引处,你可以简单地通过'productInfo.get(index).getProductPrice()'来访问它。 ArrayList并不包含你的对象,它实际上只包含它们的引用(引用存储对象的内存)。该引用与变量完全相同。像'产品myProduct'这样的变量也只存储引用。所以:'myProduct.getPrice()'和'list.get(indexOfMyProduct).getPrice();'是一样的。哦,差点忘了:'productInfo.get(1).setPrice(10);'也可以工作 – GameDroids 2014-11-08 21:35:18

+0

非常感谢。我现在知道了。但是,如果我想将产品添加到我的ArrayList中,该怎么办?一个全新的价格和一个新的数量。 ArrayList的.add方法似乎不起作用。 – user3525572 2014-11-09 22:25:28

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"); 
相关问题