Reputation: 1995
I am using a GWT CellTable and the following code does not sort correctly if the column contains NULL cells as well as cells that are not NULL:
columnSortHandler.setComparator(sixColumn, new Comparator<SectDtlsString>() {
@Override
public int compare(SectDtlsString o1, SectDtlsString o2) {
if (o1 == o2) {
return 0;
}
// Compare the Six columns.
if (o1 != null) {
return (o2 != null) ? o1.getsixPatrol().compareTo(o2.getsixPatrol()) : 1;
}
return -1;
}
});
table.addColumnSortHandler(columnSortHandler);
For example:
Black, null, null, Red - does nothing. It should return - null, null, Black, Red on first select and Red, Black, null, null - on second select
Black, Red, Brown, Tawney - returns - Black, Brown, Red, Tawney on first select and - Tawney, Red, Brown, Black - on the second select (i.e., no nulls works).
I have near identical code that refers to columns that do not contain NULLs and they sort perfectly well. I copied this code from a tutorial.
This is the result after the advice:
// Compare the Six columns.
if (o1 != null) {
if (o1 == o2) {
return 0;
}
if (o1.getsixPatrol() != null) {
if (o1.getsixPatrol() == o2.getsixPatrol()) {
return 0;
}
return o2 != null ? o1.getsixPatrol().compareTo(o2.getsixPatrol()) : 1;
}
}
return -1;
Upvotes: 0
Views: 106
Reputation: 41089
There are two problems in your code.
First, null check is in the wrong place: o1 == o2
will through exception if o1 is null. It should be:
// Compare the Six columns.
if (o1 != null) {
if (o1 == o2) {
return 0;
}
return o2 != null ? o1.getsixPatrol().compareTo(o2.getsixPatrol()) : 1;
}
Second, it's not enough to check that o1 and o2 are not null. You also need to check if o1.getsixPatrol()
and o2.getsixPatrol()
are not null before comparing them.
Upvotes: 1