I would like to know if it is alright to combine two comparators into a single comparator for two completely different classes. Objects are to be sorted alphabetically by a string type name
property which is present in both the classes which is why I created a single comparator.
/**
* Comparator to sort Book or Magazine alphabetically based on
* their String type name property.
*/
public class BookOrMagazineComparator implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2) {
if (o1 != null && o2 != null) {
if (o1 instanceof Book && o2 instanceof Book) {
Book b1 = (Book) o1;
Book b2 = (Book) o2;
return b1.getName().compareTo(b2.getName());
} else if (o1 instanceof Magazine && o2 instanceof Magazine) {
Magazine m1 = (Magazine) o1;
Magazine m2 = (Magazine) o2;
return m1.getName().compareTo(m2.getName());
}
}
return 0;
}
}
Could there by any side effect if I use the above approach?
Edit: I would like to add that Book/Magazine are actually enums.