0

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

}

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.