I read some articles written on \"ClassCastException\", but I couldn\'t get a good idea on that. Is there a good article or what would be a brief explanation?
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException For example
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
Above main method will throw below runtime class cast exception
Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable