简体   繁体   中英

Why doesn't Number use Comparable/Comparator

Short question;

I've read the Javadocs for Comparable and Comparator and I don't understand the differences. Comparable throws a NullPointerException and Comparable is implemented by many more classes, so its methods are more readily available, are they the only differences?

The second part of my question is Why doesn't Number implement Comparable but something like BigDecimal does? It would appear that only AtomicInteger and AtomicLong do not implement Comparable from the Number class. Is this why? Why aren't 'Atomic' classes Comparable?

Long Question;

I ask this because I am attempting to take a JIVariant from J-Interop convert it to a Object (has a possibility to be a Boolean, String or Number) for easy displaying and performing a switch on the return, in the event that its a Number I wish to use relational operators to determine how it compares to each individual operators.

My testing has shown that non-primitives cannot be compared, unless you are using Comparable's compareTo().

I am tempted to convert the number to something less generic to give me the functionality I require but I am concerned about overflow and memory usage. I was thinking of going BigDecimal but i know Floats have floating point precision problems. How would the more experienced StackOverflow members handle this problem?

When a class implements comparable there's only one compareTo() method. You can't define two or more compareTo() methods in one class. What if you want to compare some other values ? Then you can implement new class with comparator interface to use it with other values. Comparator interface comes to help in such case.

Number is an abstract class - there's nothing to compare there. This class is extended by concrete classess like Integer, Double etc - this classess have concrete values to compare.

Here's a great example how to use both interfaces: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

Both of these questions have been asked numerous times before. Remember that Google is your friend.

They differ in usage, logic and implementation.

在此处输入图片说明

Comparison and examples can be found on this site .

As for the second part of the question, check out this SO question . It explains why the Number class doesn't implement the Comparable interface.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM