Re: Comparable interface
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.
I do not quite understand what the problem is. Your
code was almost there. Here is an example of code
that compiles, and runs..
<sscce>
class ReportObject implements Comparable {
int positionNumber;
ReportObject(int positionNumber) {
this.positionNumber = positionNumber;
}
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;
}
public int getPositionNumber() {
return positionNumber;
}
public String toString() {
return "ReportObject: " + getPositionNumber();
}
public static void main(String[] args) {
ReportObject reportObject1 = new ReportObject(1);
ReportObject reportObject2 = new ReportObject(2);
Object object = new Object();
try {
System.out.println( reportObject2.compareTo(reportObject1) );
System.out.println( reportObject1.compareTo(reportObject2) );
System.out.println( reportObject2.compareTo(reportObject2) );
System.out.println( reportObject2.compareTo(object) );
} catch(ClassCastException cce) {
System.out.println( cce.getMessage() );
}
}
}
</sscce>
HTH
--
Andrew Thompson
http://www.athompson.info/andrew/
Message posted via JavaKB.com
http://www.javakb.com/Uwe/Forums.aspx/java-general/200704/1