I would like to know whether it is good to combine two comparators into one comparator for two completely different classes. Objects must be sorted alphabetically using the string type name, which is present in both classes, so I created one comparator.
name
/** * 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; } }
Can there be any side effect if I use the above approach?
Edit: I would add that Book / Magazine is actually listed.
, , , (AKA ).
, , , - Magazine Book (, InputStream URL, ), 0, , . , Comparator<Object>, .
Magazine
Book
InputStream
URL
0
Comparator<Object>
, , , . .
: , , - - name, NamedItem, Magazine, Book, Comparator<NamedItem> .
NamedItem
Comparator<NamedItem>
.. - . . Enum .
- , ?
. . , . , , .
- . , .
Java-, .
, , , Comparator<Book>, , List<DVD>, ; . : , DVD, .. , , , , .
Comparator<Book>
List<DVD>
, . {Aaa}, {Bbb} {Ccc}, :
return 0
(, , 0), , , . , undefined , , , ( , , , ).
, . , " " " ".
, , :
class ReadingMaterial { protected String name; //other attributes here.. } class Magazine extends ReadingMaterial { } class Book extends ReadingMaterial { }
:
class ReadingMaterialComparator implements Comparator<ReadingMaterial> { //implements comparison here.. }
, ReadMaterial, , NewsPaper. , . , .
NewsPaper