2014-11-08 80 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"); 
相關問題