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
嗨,我试图根据狗的大小来缩短 Dog 对象。我将 supermostclass 的对象 x 向下转换为 Dog 类,但不知道为什么在运行时 java 正在执行 try 和 catch 块,说 Dog 不能转换为 java.lang.Comparable