views:

589

answers:

4
+3  Q: 

Java Comparator

Does any one know of some kind of Comparator factory in Java, with a

public Comparator getComparatorForClass(Class clazz) {}

It would return Comparators for stuff like String, Double, Integer but would have a

public void addComparatorForClass(Class clazz, Comparator comparator) {}

For arbitrary types.

+11  A: 

Instead of:

factory.getComparatorForClass(x.getClass()).compare(x, y)

you could simply implement Comparable and write:

x.compareTo(y)

String, the primitive wrappers, and standard collections already implement Comparable.

ngn
+2  A: 

I'm not aware of anything like that off the top of my head. If you really need something like this, it shouldn't be too difficult to implement one yourself.

However, could you elaborate on why you need something like this? There typically should not be a "default" comparator for classes. If the class has some sort of natural ordering, you really ought to have it implement java.lang.Comparable, and implement Comparable#compareTo(Object) : int instead.

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

Jack Leow
+1  A: 

Comparator are need to be extend.. this is based on the reusable code implementation.. in these method you can have a custom comparison of data.. the implementation is just simple.. just implement the Comparator interface.. override its compareto method and place the comparison code.. and return which you think is greater in terms of values..

Aristotle Ucab