简体   繁体   中英

How do I store and then access a class object in an ArrayList?

So I have this class called Product that stores information about a product, particularly it's name, it's price, and it's quantity. It looks like this:

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

}

I want to then use the setFromLine method to read in a line from a file, a line that looks like

<product> <price> <quantity>

separated by white space, and set the appropriate fields given that line, which is what that should do. But, then I want to store that in an ArrayList field I have in my driver program. Right now I have a method in my driver program that looks like this:

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

So, my question is: if my code is correct, how do I go about accessing specific parts of the information I stored in the ArrayList . For instance, if I want to access information about a product Lamp which has a price 15.3 and a quantity 200 and it's the first thing read in the file and stored in the ArrayList , what line of code can I write to get it's price specifically or it's quantity specifically, etc. My ArrayList field in my driver program looks like this, btw:

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

If you don't want to iterate through the whole list, you could also implement the equals method of your Product so that it would compare two products by its name. It sounds complicated but it is actually quite efficient :)

put in your Product class:

@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
}

now after putting that into your Product class you can search your ArrayList like that:

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

in detail:

you create a new instance of the Product you are searching for and set its name. Then you check your list if it contains that product (you do that by calling productInfo.contains(product) . The contains method will compare the products in the list with your new product by using the equals method you just implemented above (and the equals method compares by the product's name)

If there is a Product in you list with by name, you can get it's index by calling productInfo.indexOf(product) . (this method actually uses the same equals method and works exactly as the contains method, only now it returns the index of the element instead of a boolean )

With that index you can call productInfo.get(index) and you will get your product from the list with all it's data you want to know.

EDIT:
Here some additional methods than may come in handy:

Adding a new Item

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

Add another list to your 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

Test if list is empty

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

Turn the list into an array

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.

Assuming your ArrayList is named productInfo you would have to cycle through it like this and search for the product that is matching the name you are trying to query for:

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

But in this case you might be better of using a HashMap which assigns a value (in your case a product) to a key (in your case its name). You can then quickly access the value for a key like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM