How to simplify a null-safe compareTo() implementation?
You can simply use Apache Commons Lang: result = ObjectUtils.compare(firstComparable, secondComparable)
You can simply use Apache Commons Lang: result = ObjectUtils.compare(firstComparable, secondComparable)
For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest. I would do either int cmp = a > b ? +1 : … Read more
Using Java 8, you can easily build the comparator you need: Arrays.sort(fClasses, Comparator.nullsFirst(Comparator.naturalOrder())); Use nullsLast instead if that’s what you want, of course.
see this: From http://www.oracle.com/technetwork/java/javase/compatibility-417013.html#source Area: API: Utilities Synopsis: Updated sort behavior for Arrays and Collections may throw an IllegalArgumentException Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced. The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract. The previous implementation silently … Read more
This is the right way to compare strings: int studentCompare = this.lastName.compareTo(s.getLastName()); This won’t even compile: if (this.getLastName() < s.getLastName()) Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead. So to compare fist/last name order you need: int d = getFirstName().compareTo(s.getFirstName()); if (d == 0) d = getLastName().compareTo(s.getLastName()); return d;
The answer is in the JavaDoc of the equals() method: Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method). In other words: equals() checks if the BigDecimal objects are exactly the same in every … Read more
A difference is that “foo”.equals((String)null) returns false while “foo”.compareTo((String)null) == 0 throws a NullPointerException. So they are not always interchangeable even for Strings.