Explanation of “ClassCastException” in Java

前端 未结 12 1849
小蘑菇
小蘑菇 2020-11-21 11:12

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?

12条回答
  •  一整个雨季
    2020-11-21 11:46

    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

提交回复
热议问题