Error sorting list using Collections.sort
I'm getting a NullPointerException
when i try to sort a list with by doing the Collections.sort(list2)
the list contains the following strings
[BOOTH 4, ENP ROOM, BOOTH 6, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, BOOTH 7, BOOTH 3, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 1, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, BOOTH 10, C&T Waiting Area, C&T Waiting Area, C&T Wai开发者_C百科ting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, C&T Waiting Area, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
Do i need to use comparator for this list?
You could use a comparator that can handle null values. E.g.
private static final class NullsFirstComparator implements Comparator<String> {
public int compare(String lhs, String rhs) {
if (lhs == rhs)
return 0;
if (lhs == null)
return -1;
if (rhs == null)
return 1;
return lhs.compareTo(rhs);
}
}
Which will sort the null values first (they are less than everything)
Remove null
values before sorting. They can't be sorted
You can also use NullComparator
in Apache commons. It provide lot of useful utilities for writing comparator
精彩评论