You are viewing a plain text version of this content. The canonical link for it is here.
Posted to common-user@hadoop.apache.org by Shevek <ha...@anarres.org> on 2009/05/04 14:54:01 UTC

Re: Implementing compareTo in user-written keys where one extends the other is error prone

On Sun, 2009-05-03 at 23:38 -0700, Sharad Agarwal wrote:
> Marshall Schor wrote:
> >
> > public class Super implements WritableComparable<Super> {
> >  . . .
> >   public int compareTo(Super o) {
> >     // sort on string value
> >     . . .
> >   }
> >
> > I implemented the 2nd key class (let's call it Sub)
> >
> > public class Sub extends Super {
> >  . . .
> >   public int compareTo(Sub o) {
> >     // sort on boolean value
> >     . . .
> >     // if equal, use the super:
> >     ... else
> >      return super.compareTo(o);
> >   }
> >
> The overridden method must have same arguments as the parent class
> method. Otherwise it is just another method, not an overridden one.
> In your case, if the current code looks like error prone, you can
> make Super also as a template. Then you can use the Sub class in
> the compareTo method However you will have to cast in the
> Super class.

In this particular case, I _think_ making Sub implement Comparable<Sub>
will be sufficient since then javac will also generate public volatile
int compareTo(Object o) { compareTo((Sub)o); } which overrides the
volatile method in the superclass. Overriding compareTo(Super) is not
required. See my post to general@hadoop for more details.

S.

> class Super<T> implements WritableComparable<T> {
>   public int compareTo(T o) {
>    Super other = (Super) o;
>    ....
>   }
> }
> 
> class Sub extends Super<Sub> {
>   public int compareTo(Sub o) {
>     ...
>   }
> }
> 
> -Sharad