Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between removeAllElements() and clear() for DefaultListModel?

What is the difference between removeAllElements() and clear() method of DefaultListModel in java swing?

The java docs for DefaultListModel says :-

public void clear()

Removes all of the elements from this list. The list will be empty after this call returns (unless it throws an exception).

and

public void removeAllElements()

Removes all components from this list and sets its size to zero.

So both basically removes all elements from list so what is the difference? How to decide when to use which?

like image 284
Harry Joy Avatar asked Jan 27 '26 06:01

Harry Joy


1 Answers

They are both same.

DefaultListModel uses a Vector under the hood.
The clear() method was added later when Vector was re-written to fit into the Collection API's.

With version 1.3 the Collections API made its' entrance so the Vector was re-written to fit into the List interface.

In order for it to be backwards compatible, they simply forwarded the calls to the old existing methods where available & possible.

EDIT

From Java Source:

/**
 * Removes all components from this list and sets its size to zero.
 * <blockquote>
 * <b>Note:</b> Although this method is not deprecated, the preferred
 *    method to use is <code>clear</code>, which implements the 
 *    <code>List</code> interface defined in the 1.2 Collections framework.
 * </blockquote>
 *
 * @see #clear()
 * @see Vector#removeAllElements()
 */
public void removeAllElements() {

        int index1 = delegate.size()-1;
        delegate.removeAllElements();

        if (index1 >= 0) {
            fireIntervalRemoved(this, 0, index1);
        }

}
like image 158
Kerem Baydoğan Avatar answered Jan 28 '26 19:01

Kerem Baydoğan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!