简体   繁体   中英

How to know if two objects are comparable to each other?

I would like to write universal comparator, which can compare objects of any class. I would like numbers go first, then strings, then all other comparable objects.

First I wrote

@SuppressWarnings({ "unchecked", "rawtypes" })
            @Override
            public int compare(Object o1, Object o2) {

                if( o1 instanceof Number && !(o2 instanceof Number) ) {
                    return -1;
                }
                else if( o2 instanceof Number && !(o1 instanceof Number) ) {
                    return +1;
                }
                else if( o1 instanceof String && !(o2 instanceof String) ) {
                    return -1;
                }
                else if( o2 instanceof String && !(o1 instanceof String) ) {
                    return +1;
                }
                else if( o1 instanceof Comparable && !(o2 instanceof Comparable) ) {
                    return -1;
                }
                else if( o2 instanceof Comparable && !(o1 instanceof Comparable) ) {
                    return +1;
                }
                else if( o1 instanceof Comparable && o2 instanceof Comparable ) {
                    return ((Comparable)o1).compareTo(o2);
                }
                else {
                    return o1.hashCode() - o2.hashCode();
                }
            }

I was thinking the check

o1 instanceof Comparable && o2 instanceof Comparable

will give me comparing within numbers, strings and all other comparable classes.

But then I found that Number is not comparable, ie I can't compare doubles with integers with it.

Also I found, that Comparable<T> contract is fuzzy. Although T can be any class, actually it probably should be the same class which implements it...

So, how to accomplish?

Suppose sometime in the future you create some instances of class Apple and the some instances of class Orange. How could the universal comparison algorithm that you write today possibly compare those Apple instances to the Orange instances in the future? I think you need to rethink what you are trying to accomplish and perhaps make sure your objects are of the same class before trying to compare them.

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