0

I'm currently working on a shopping cart program, the program works by adding objects to an ArrayList that then gets printed on a JTextArea . The program needs to have the functionality of removing items as well. The user will input a unique order number of the order they would like to remove, I know how to get the number they have inputted, but I don't know how I can then use that number to run through my Array and delete the correct object.

5
  • 2
    Iterate through the list, compare that number and remove the matching one. Commented Jul 24, 2013 at 9:33
  • ArrayList.remove() method doesn't work ? Commented Jul 24, 2013 at 9:34
  • how can I compare the number they entered with attributes of objects in the array list? Commented Jul 24, 2013 at 9:36
  • @radimpe That is not a duplicate. The question is not a duplicate (which is the core criteria), but even the selected answer isn't really relevant. Commented Jul 24, 2013 at 11:35
  • The closure went ahead anyway. I've voted to re-open - the suggested duplicate is not valid. Commented Jul 24, 2013 at 13:27

1 Answer 1

3

Use an Iterator to loop around your objects. Compare the relevant field in the object with the value from the user. If you get a match, remove the object and stop searching.

Iterator<OrderObject> iterator = yourList.iterator();
boolean found = false;

while (iterator.hasNext()) {
  OrderObject o = iterator.next();
  if (o.getSomeField() == numberFromUser) {
    iterator.remove();
    found = true;
    break;
  }
}

if (!found) {
   // opportunity here to alert user?
}
Sign up to request clarification or add additional context in comments.

2 Comments

Iterator<OrderObject> iterator = yourList.iterator(); while (iterator.hasNext()) { OrderObject o = iterator.next(); if (o.someField == numberFromUser) { iterator.remove(); break; } }
I think he gave you the same code which you put in the comment. What you want to imply by that?

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.