Wednesday, 28 August 2013

try to sort arrays using compareTo() but getting error

try to sort arrays using compareTo() but getting error

public class Dog {
int size;
String name;
//Deploying a constructor
Dog(String name, int size){
this.name=name;
this.size=size;
}
//Deploying toString() for printing
public String toString(){
return name+"/"+size;
}
//Deploying compareTo() method and overriding it for int value
public int compareTo(Object s){
return (this.size-((Dog)s).size);
}
}
import java.util.Arrays;
public class CompareTo {
public static void main(String[] args){
Dog[] obj=new Dog[5];
obj[0]=new Dog("Alpha",332);
obj[1]=new Dog("Romeo",32);
obj[2]=new Dog("Charlie",332);
obj[3]=new Dog("Tyson",632);
obj[4]=new Dog("Roger",532);
//Without Sorting taking the output
for(Object x:obj){
System.out.println(x);
}
//With Sorting taking the output
try{Arrays.sort(obj);
for(Object x: obj){
System.out.println(x);
}
}catch(Exception e){
System.out.println("Something is wrong in this line"+e);
}
}
}
Output-Alpha/332
Romeo/32
Charlie/332
Osama/632
Laden/532
Something is wrong in this linejava.lang.ClassCastException: Dog cannot be
cast to java.lang.Comparable
Hi, I was trying to short the Dog object on the basis of size of the dogs.
I downcast object x of supermostclass to Dog class but don't know why at
runtime java is executing the try and catch block saying that Dog can't be
cast to java.lang.Comparable

No comments:

Post a Comment