Explanation of “ClassCastException” in Java

前端 未结 12 1680
小蘑菇
小蘑菇 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:48

    A very good example that I can give you for classcastException in Java is while using "Collection"

    List list = new ArrayList();
    list.add("Java");
    list.add(new Integer(5));
    
    for(Object obj:list) {
        String str = (String)obj;
    }
    

    This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

提交回复
热议问题