1

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 Waiting 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?

2
  • 5
    "I'm getting an exception" is not a useful error report. Stack traces are there for a reason. Commented Dec 8, 2010 at 10:02
  • @user521180 which exception?some stack trace or code would actually help you Commented Dec 8, 2010 at 10:03

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

Comments

2

Remove null values before sorting. They can't be sorted

2 Comments

Strictly, they can be sorted, but only if you provide a Comparator object that does something sensible with null references.
@Stephen C - Yes, you are right. Couldn't see any comparators in the invocation: Collections.sort(list2)
1

You can also use NullComparator in Apache commons. It provide lot of useful utilities for writing comparator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.