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?
import 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]