-6

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?

Philipp Wendler
  • 11,184
  • 7
  • 52
  • 87

7 Answers7

4

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

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

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.

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
3

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();
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

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

        }
    });
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Add an ActionListener to your button where you set

orderItems = new ArrayList();

That would delete every item in the list.

Adrian Jandl
  • 2,985
  • 4
  • 23
  • 30
0

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

Manish Doshi
  • 1,205
  • 1
  • 9
  • 17
0

You can empty the ArrayList by calling the clear method

orderItems.clear();

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64