|
Re: TreeViewer Sorter [message #792720 is a reply to message #792132] |
Tue, 07 February 2012 10:20 |
Daniel Krügler Messages: 853 Registered: July 2009 |
Senior Member |
|
|
On 2012-02-06 17:51, budili Mising name wrote:
> i want to sort my elements in a TreeViewer. I have a special order for
> my elements, which look for example like this:
> Quote:
>> - Item P1 - Item P2
>> - Item P3
>> - Item P4
>> - Item P4.1 (child item; father is P4)
>> - Item P4.2 (child item; father is P4)
>> - Item P4
>> - Item P4.1 (child item; father is P4)
>> - Item P4.2 (child item; father is P4)
I don't understand the position of P2: Is this a tree with several columns?
> The Items P1-P3 are different objects and have to be on the top of the
> tree.
> P4 comes always after P3 and have child items. It is possible to have a
> lot of P4 items. How i have to implement the ViewerComparator?
>
> Here is my example:
> @Override
> public final int compare(final Viewer viewer, final Object object1,
> final Object object2)
> {
> final String name1 = object1.toString();
> final String name2 = object2.toString();
> if (name1.equals("P1") || name2.equals("P1"))
> {
> return 1;
> }
> if (name1.equals("P2") || name2.equals("P2"))
> {
> return 1;
> }
> if (name1.equals("P3") || name2.equals("P3"))
> {
> return 1;
> }
> if (name1.equals("P4.1") || name2.equals("P4.1"))
> {
> return 1;
> }
> if (name1.equals("P4.2") || name2.equals("P4.2"))
> {
> return 1;
> }
> return super.compare(viewer, object1, object2);
> }
>
> But this workaround does not work always. Can someone help me?
Your compare function does not induce a strict weak ordering, this would
require that the properties irreflexivity, asymmetry, and transitivity
would hold. Simple proof: According to your test
"P1" compared to "P1" would return 1, which makes no sense the result
would need to be 0. In other words: This is no valid ordered comparison.
The right fix is to ensure that the different name parts are compared in
hierarchic order. There are several ways of fixing this, here is one way:
static int compare(String[] a, String[] b) {
final int len = Math.min(a.length, b.length);
for (int i = 0; i < len; ++i) {
int res = a[i].compareTo(b[i]);
if (res != 0)
return res;
}
return a.length - b.length;
}
@Override
public final int compare(final Viewer viewer, final Object object1,
final Object object2)
{
final String name1 = object1.toString();
final String name2 = object2.toString();
return compare(name1.substring(1).split("\\."),
name2.substring(1).split("\\."));
}
[The underlying assumption here is that there is only a single letter -
you refer to "P" solely - before the numbers. You have to adapt this
code, if that assumption does not hold]
HTH & Greetings from Bremen,
Daniel Krügler
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.01940 seconds