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.
-
2Iterate through the list, compare that number and remove the matching one.jlordo– jlordo2013-07-24 09:33:28 +00:00Commented Jul 24, 2013 at 9:33
-
ArrayList.remove() method doesn't work ?Dheeraj Joshi– Dheeraj Joshi2013-07-24 09:34:08 +00:00Commented Jul 24, 2013 at 9:34
-
how can I compare the number they entered with attributes of objects in the array list?user2613957– user26139572013-07-24 09:36:25 +00:00Commented 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.Duncan Jones– Duncan Jones2013-07-24 11:35:23 +00:00Commented Jul 24, 2013 at 11:35
-
The closure went ahead anyway. I've voted to re-open - the suggested duplicate is not valid.Duncan Jones– Duncan Jones2013-07-24 13:27:52 +00:00Commented Jul 24, 2013 at 13:27
Add a comment
|
1 Answer
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?
}
2 Comments
user2613957
Iterator<OrderObject> iterator = yourList.iterator(); while (iterator.hasNext()) { OrderObject o = iterator.next(); if (o.someField == numberFromUser) { iterator.remove(); break; } }
Sandiip Patil
I think he gave you the same code which you put in the comment. What you want to imply by that?