Fred Trellis Fred Trellis - 1 year ago 71
Java Question

SWT Snippet2. Table sorting. items array changes in the loop. How does this work?

I am trying in SWT to add sorting to a table widget. Copying the code from Snippet2
Handler doesn't work. It correctly swaps two items into sorted order. More than 2 items in the table, and the results are unpredictable.

It seems to me (in the following code extract from Snippet2
) that
is going to change the array of
called items that we are iterating over in the outer for loop,
for (int i = 1 ......
Also, when one item is
, and inserted into items at a new index, the whole array is recreated afresh. That surely breaks the iteration?

So, I guess I have two questions:

  1. What am I not understanding about Snippet2's algorithm?

  2. Is there any other obvious reason why a sort operation might return random results (bearing in mind I am a noob, so am likely to have made the stupidest of mistakes)?

Here is my code:

Listener sortListener = new Listener() {
public void handleEvent(Event e) {
TableItem[] items = table.getItems();
Collator collator = Collator.getInstance(Locale.getDefault());
TableColumn column = (TableColumn)e.widget;
int index = column == column1 ? 0 : 1;
for (int i = 1; i < items.length; i++) { <--------- HERE
String value1 = items[i].getText(index);
for (int j = 0; j < i; j++){
String value2 = items[j].getText(index);
if (, value2) < 0) {
String[] values = {items[i].getText(0), items[i].getText(1)};
items[i].dispose(); <--------- HERE
TableItem item = new TableItem(table, SWT.NONE, j);
items = table.getItems(); <--------- HERE


Answer Source

You may want to use JFace wrapper for SWT table (org.eclipse.jface.viewers.TableViewer), which gives your table more built in features. I suggest this tutorial for JFace TableViewer. Here is tutorial for sorting TableViewer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download