Removing Items from a List

Just as you must add items to the list, it is often necessary to remove items from the list while the application is running. This is most often done to remove a selection that is no longer valid given program conditions.

How do I do that?

To remove an item from the list, you use the appropriate version of the remove( ) method, or you use removeAll() to clear the contents of the list.

To remove a single item, use this:

l.remove(3);

This removes the item that resides at index 3, or the fourth item in the list.

You can also use a version of remove( ) to eliminate more than one item from a list. One way to code for that task is to specify a range of items to remove. Figure 7-3 results from adding the following line to the code that created Figure 7-2:

l.remove(1,3);
Results of removing a range of items

Figure 7-3. Results of removing a range of items

You can also use a version of remove( ) that accepts an array of integers that instruct the method which items to remove:

int n[] = {1,3,5};
l.remove(n);

This yields Figure 7-4 when added to ListExample, shown in Example 7-2, after the code in which the list is initially populated.

Removing items using an int array

Figure 7-4. Removing items using an int array

Finally, you can remove a single item by referencing it by its String value:

l.remove("Item One");

This version of remove( ) starts at the ...

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.