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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.