开发者

how to compare on multiple classes in java?

Right now, I have written at comparator that sorts an array of Integers and Strings. As you can see from the code, if the two classes aren't the same, then the String class takes the greater than value. However, this only allows for two classes. What if I want to add another primitive type to my array, such as Float? I'd have to add more code to to if-else statement. Is there a way to implement compare without having to add a statement for each additional class I want to compare?

i开发者_运维技巧mport java.util.Arrays;
import java.util.Comparator;

public class SampleComparator implements Comparator<Object> {

public static void main(String[] args) {
    Object[] inputData = { new String("pizza"), new Integer(0),
            new String("apples"), new Integer(5), new String("pizza"),
            new Integer(3), new Integer(7), new Integer(5) };
    Arrays.sort(inputData, new SampleComparator());
    System.out.println(Arrays.asList(inputData));
}

public int compare(Object o1, Object o2) {
    if (o1.getClass().equals(o2.getClass())) {
        return ((Comparable)o1).compareTo((Comparable)o2);
    } else {
        if(o1.getClass().getCanonicalName().equals("java.lang.String")){
            return 1;
        } else {
            return -1;
        }
    }

}

 }

output:

[0, 3, 5, 5, 7, apples, pizza, pizza]


I'd have to add more code to to if-else statement. Is there a way to implement compare without having to add a statement for each additional class I want to compare?

You probably want to compare objects of the same class using their native comparators, and then have some order on the classes (e.g.. all ints before all floats before all strings).

So you could compare the classes first, and then if equal compare the objects.

public int compare(Object o1, Object o2) {
    // maybe some null checks here?

    if (o1.getClass().equals(o2.getClass())) {
        // and what if they are not Comparable ?
        return ((Comparable)o1).compareTo((Comparable)o2);
    } else {
        // for example compare by class name alphabetically
        // another idea would be a map with all supported classes,
        // assigning them an order

        return o1.getClass().getName().compareTo(o2.getClass().getName());
    }

}

It will be difficult to come up with a meaningful comparison of unknown classes. You probably need to make up a list of supported classes and explicit rules how you want them compared.


If you just want to make sure you group classes together, you could do something like

    ...
} else {
    return o1.getClass().getName().compareTo(o2.getClass().getName());
}


You can always compare the toString() representation:

public int compare(Object o1, Object o2) {
    return o1.toString().compareTo(o2.toString());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜