简体   繁体   中英

Accesing and object in an arraylist (java)

I am working on an order program similar to the self checkout counters at supermarkets. While an order is being created, each line item is an object and is kept in an arraylist.
The LineItem class has two variables - ItemID and ItemQuantity. A method, incQuantity is used to increment the quantity by 1. I have no problem creating the arraylist and adding lineItems to it, but am not able to call the incQuantity method to be used when additional items with the same ItemID are encountered. I am using a get, remove, and add sequence to update the object. It seems to me that there must be a way to access the object directly and call the incQuantity method without the overhead of removing it from the arraylist and adding it again. See test code below.

 public static class LineItem{
    private String ItemID ;
    private int ItemQuantity;

    public LineItem(String ID) {
      ItemID = ID;
      ItemQuantity = 1;  //upon first occurrence of an item, qty is initialized to 1
}
    public void incQuantity() {

    ItemQuantity++;
} 
}



private static void TestItems() {
        ArrayList <LineItem> orderSheet = new ArrayList<LineItem>();
        LineItem newLine = new LineItem("12345");
        orderSheet.add(newLine); 
        newLine = new LineItem("121233445");
        orderSheet.add(newLine); 
        newLine = new LineItem("129767345");
        orderSheet.add(newLine); 
        newLine = new LineItem("5454120345");
        orderSheet.add(newLine); 
        newLine = new LineItem("0987123125");
        orderSheet.add(newLine); 
        newLine = new LineItem("65561276345");
        orderSheet.add(newLine); 
        // Increment Quantity of Element 0 below
        LineItem updateLine = orderSheet.get(0);
        updateLine.incQuantity();
        orderSheet.remove(0);
        orderSheet.add(updateLine);

}

You don't have to remove an re-add it, just fetch the item and call its method:

orderSheet.get(0).incQuantity() should do the trick.

My suggestion would be use a simple Hashmap to solve this problem. The map will simply consist the item id as the key and the item class as the value. The item class will also have an increment counter method. This way you check if the item id is on the map and if so call the method to increase the count.

Please see this. I am giving an example of increasing the quantity of all item in orderSheet. But i Think you need to check the item id during call incQuantity().

Iterator<LineItem> it = orderSheet.iterator();
while(it.hasNext()) {        
    it.next().incQuantity();
}   

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