I have an ArrayList:
ArrayList<OrderItem> orderItems = new ArrayList<OrderItem>();
It is filled with objects. I want to press a button that would effectively delete all the objects in this list. How can I do this?
I have an ArrayList:
ArrayList<OrderItem> orderItems = new ArrayList<OrderItem>();
It is filled with objects. I want to press a button that would effectively delete all the objects in this list. How can I do this?
Use clear() method
orderItems.clear();
And
The main thing to be concerned about is what other code might have a reference to the list.
Prefer to read @Skeets answer : Better practice to re-instantiate a List or invoke clear()
Use clear() method like this orderItems.clear()
It Removes all of the elements from this list. The list will be empty after this call returns.
You can use ArrayList#clear() .
Removes all of the elements from this list. The list will be empty after this call returns.
With clear()
, you don't need to create a new ArrayList
object . It just empties the ArrayList
.
orderItems.clear();
orderItems.trimToSize();
Collection interface itself defines a void clear();
method.
/**
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this collection
*/
In your buttons actionListner just use orderItems.clear();
. This will remove all elements of that Collection(ArrayList in your case).
myButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
orderItems.clear();
}
});
Add an ActionListener
to your button where you set
orderItems = new ArrayList();
That would delete every item in the list.
There is one inbuilt method in ArrayList.So you can implement it on orderdItems like:
orderedItems.clear()
Also check this: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
You can empty the ArrayList by calling the clear method
orderItems.clear();