Inserting Items in the Middle of a List

Sometimes it is necessary to add items to a list that has already been populated. At such times, you often need to cause new items to appear in the middle of the list, instead of adding them to the end.

How do I do that?

There are two versions of the add() method. As you saw in Example 7-1, the first version appends items to the list in the order in which the method is called. Each successive add causes the item to appear at the bottom of the list.

It is possible to insert an item at any position in the list using the second form of add( ), which accepts a second parameter to specify the index location after which the item should appear. Consider the following code:

l.add("Item One");
l.add("Item Two");
l.add("Item Three");
l.add("Item Four");
l.add("Item Five");    
l.add("Three and a Half", 3);

Changing ListExample to use this code will result in Figure 7-2.

Results of inserting an item in the middle of a list

Figure 7-2. Results of inserting an item in the middle of a list

Tip

Although indexing of the list begins with zero, which is the Java convention, if you consider the second parameter of the add( ) method to be the index number of the item after which you want to insert the item, you will not need to mentally perform the calculation of counting by zero. Otherwise, you must think of the parameter as the index of the item before which you want to insert the item, or as the index that will be taken ...

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.