Re: Comparable interface
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Andrew Thompson schreef:
Chanchal wrote:
..
this is the code i have written
Please read my original message again, carefully.
If there is anything that I did not make clear about
helping the reader, feel free to ask.
..
in this case if i do not return some thing even in the case of
throwing the exception, i have to retrn some value. otherwise the
class wont compile.
public int compareTo(Object obj){
ReportObject rObj;
if(obj instanceof ReportObject ){
rObj = (ReportObject)obj;
if(this.positionNumber < rObj.getPositionNumber()){
return -1;
}else if(this.positionNumber == rObj.getPositionNumber()){
return 0;
}else if(this.positionNumber > rObj.getPositionNumber()){
return 1;
}
}else{
throw new ClassCastException(this +
" is not comparable to " + obj );
}
return -2;
}
Funny, I would have expected a compiler error here about unreachable
code. The last line is unreachable, right?
Ah, no, it isn???t. At least, the compiler cannot know: obj can be an
instance of ReportObject, and the getPositionNumber() method can vary
such that none of the inner conditions fits.
Anyway, why not simply
public int compareTo(Object obj){
ReportObject rObj = (ReportObject)obj;
if(this.positionNumber < rObj.getPositionNumber()){
return -1;
}else if(this.positionNumber == rObj.getPositionNumber()){
return 0;
}else if(this.positionNumber > rObj.getPositionNumber()){
return 1;
}
}
The JVM will throw the ClassCastException, no need to do that yourself.
And oh yes, you might try to venture into generics, in which case the
problem will go away all by itself:
class ReportObject implements Comparable<? super ReportObject> {
....
public int compareTo(ReportObject obj){
if(this.positionNumber < obj.getPositionNumber()){
return -1;
}else if(this.positionNumber == obj.getPositionNumber()){
return 0;
}else if(this.positionNumber > obj.getPositionNumber()){
return 1;
}
}
....
}
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFGLKswe+7xMGD3itQRAlkEAJ9toexDQy7jxIoKcEZ9Klz8F7QtewCeMbwT
T0zzFTarIAEWEokIjgPF3Ds=
=DlXb
-----END PGP SIGNATURE-----