Explanation of “ClassCastException” in Java

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

    A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class ClassCastExceptionExample {
    
      public ClassCastExceptionExample() {
    
        List list = new ArrayList();
        list.add("one");
        list.add("two");
        Iterator it = list.iterator();
        while (it.hasNext()) {
            // intentionally throw a ClassCastException by trying to cast a String to an
            // Integer (technically this is casting an Object to an Integer, where the Object 
            // is really a reference to a String:
            Integer i = (Integer)it.next();
        }
      }
     public static void main(String[] args) {
      new ClassCastExceptionExample();
     }
    }
    

    If you try to run this Java program you’ll see that it will throw the following ClassCastException:

    Exception in thread "main" java.lang.ClassCastException: java.lang.String
    at ClassCastExceptionExample  (ClassCastExceptionExample.java:15)
    at ClassCastExceptionExample.main  (ClassCastExceptionExample.java:19)
    

    The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

提交回复
热议问题