user4235730 user4235730 - 1 year ago 82
Java Question

What is the purpose of the method?

Java 7 introduced the

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

over simply calling, right);

is only
-safe if
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, right)
throws a
if all of
, while
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 Source

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 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, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download