Best Practice in handling comparator
-
12-11-2019 - |
سؤال
How to handle null objects, which comes in compareTo method. This always causes nullpointer exception. What a is best way to solve this issue.
المحلول
public int compareTo(Object to) {
if (to == null) return Integer.MIN_VALUE;
// Now knowing it's not null, continue as before
}
نصائح أخرى
You can check the object before you call "compareTo" method.
like this:
if(obj != null){
//TODO
}
From the fine documentation on Comparable:
Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
Don't put null in a sorted collection if you don't want to handle NullPointerExceptions.
لا تنتمي إلى StackOverflow