• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics and Comparator best practices  RSS feed

 
Brian Buckley
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Brian Buckley
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!