user4235730 user4235730 - 5 months ago 24
Java Question

What is the purpose of the Objects.compare() method?

Java 7 introduced the

class containing “
null
-safe or
null
-tolerant” methods, including
compare(T, T, Comparator<T>)
. But when would I ever use

Objects.compare(left, right, comparator);


over simply calling

comparator.compare(left, right);


?

Objects.compare
is only
null
-safe if
comparator
is as well, so why would I wrap the compare-call? The optimization of first checking for object identity seems like something that should be done in the comparator itself. And the only real difference in behavior I can see is that
comparator.compare(left, right)
throws a
NullPointerException
if all of
comparator
,
left
and
right
are
null
, while
Objects.compare
does not; this does not really seem like an important enough consideration to warrant a new standard library method.

Am I missing something obvious here?

Answer

This was interesting to dig into. The Objects class, along with this .compare() method, was introduced in 3b45b809d8ff by Joe Darcy, and the commit message cites Bug 6797535 and indicates "Sherman" (Xueming Shen?) signed off on it. In addition to the bug there is this thread from Sept. 2009 discussing what features to add to Objects. In the thread folks discuss adding compare(int, int) (and the like) primitive comparison methods, and eventually decide these should reside in their respective wrapper classes (see Integer.compare()). This method is introduced later in that thread but without any commentary that I can find.

Later a patch is sent out for review containing Objects.compare(), and Joshua Bloch replies:

I don't think you should add this method ( compare(T a, T b, Comparator c)). Its utility is unclear, and it doesn't have the power-to-weight ratio of the other methods in this class.

Darcy responds:

Yeah, I included this with "Item 12: Consider implementing Comparable" from EJv2 in mind.

It's not clear to me what this method brings to the table regarding Item 12, but the issue doesn't appear to have been raised again. I infer that the intent was to provide a method equivalent to the primitive compare()'s for stylistic reasons, but I haven't found evidence that was actually the intent.


It's worth noticing that in the same exchange between Darcy and Bloch the Objects.toString() method is similarly criticized by Bloch:

I would definitely /not/ add this method (Objects.toString). It brings nothing to the table that isn't already there. People know and use String.valueOf. Let's not muddy the waters by adding another choice.

But as we know it was not removed, Darcy simply responded:

So noted.


So in conclusion, it seems to me like this was introduced without much intent. It was proposed and the objections that were raised did not block it being checked in. I imagine that a more rigorous design review would have erred on the side of leaving it out, like Bloch suggested.

Comments