Java record-44-Object array trap

Source: Internet
Author: User

Java record-44-Object array trap
Below is a very simple program, but there are unexpected traps:

    public static void main(String[] args) {        ArrayList list = new ArrayList();        list.add(new Integer(1));        list.add(new Integer(2));         //      Integer[] ins = (Integer[])list.toArray();                Object[] ins = list.toArray();        for(int i=0;i<ins.length;i++){            System.out.println(ins[i]);        }    }

 

The above program can be executed, no problem. However, the annotated line of code throws the following exception during runtime:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;            at my.arraylist.ArrayListTest.main(ArrayListTest.java:16)

 

Integer[] ins = (Integer[])list.toArray();

 

List. the toArray () method returns an array of Object [], and the array of Object [] is forcibly converted to an Integer [] array. The literal understanding is correct and there is no problem during compilation, however, an exception is thrown during running. Why? The preceding example shows that the Object [] array cannot be forcibly converted to an Integer [] array. The Integer Object inherits the Object, but the Integer [] array does not inherit the Object [] array. The literal understanding does not seem to work. For a deeper understanding, the Object [] array can not only store Integer objects, but also objects such as strings. If an Object [] array stores Integer objects, string objects, and Boolean objects; if the Object [] array is forcibly converted to an Integer [] array, the string and Boolean objects cannot be converted to Integer objects. Next article: http://www.bkjia.com/kf/201510/447439.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.