Should Foo be written like version 1 or version 2 below? What are the considerations for choosing between the two? Are there any upsides or downsides for one or the other?
class Foo implements Comparator{ ... public int compare(Object o1, Object o2) { ... } }
class Foo implements Comparator<Foo>{ ... public int compare(Foo foo1, Foo foo2) { ... } }
Opinions welcome.
Brian
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Generics will give you more typesafety.
Your second example looks a little bit strange, though: a Comparator typically shouldn't compare instances of itself - that sounds more like a Comparable.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Brian Buckley
Greenhorn
Joined: Jan 12, 2003
Posts: 7
posted
0
Thanks. As you point out, my original example should have read like below. The second has the type safety. So why ever use the first anymore?
class Foo implements Comparable{ ... public int compareTo(Object o) { ... } }
class Foo implements Comparable<Foo>{ ... public int compareTo(Foo foo) { ... } }
Brian
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Well, to me the only reason not to use generics in that case would be that the code had to compile with Java 1.4...
Jeroen Wenting
Ranch Hand
Joined: Oct 12, 2000
Posts: 5093
posted
0
the signature of compareTo prior to Tiger is 'public int compareTo(Object o)', which should answer your question. In Tiger it's been changed to 'public int compareTo(T o)' allowing your second option.
You have to ask yourself whether you will ever have your class in a situation where it may have to be compared to other types that cannot be resolved to Foo in some way and what you want to do if that happens. Will you be content with the runtime error generated by the JVM or would you like to do your own error handling inside the method.