Java record -44-object Array traps

Source: Internet
Author: User

The following 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.

But the line of code that is commented on runs throws the following exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; Cannot is cast to [Ljava.lang.Integer; At My.arraylist.ArrayListTest.main (arraylisttest.java:16)
integer[] ins = (integer[]) List.toarray ();

The List.toarray () method returns the object[] array, object[] array cast to the integer[] array, the literal understanding is no problem, the compile time is OK, but the runtime throws an exception, which is why?

    1. The above example confirms that the object[] array cannot be coerced into a integer[] array without doubt.

    2. The integer object inherits the object, but the integer[] array does not inherit the object[] array, and the literal understanding does not seem to make sense.

    3. A deeper understanding of the object[] array is not just about storing an integer object, it can also store objects such as strings and so on.

    4. If an object[] array holds an integer object, also holds a string object, and a Boolean object is stored, then there is a problem when the object[] array is cast to the integer[] array. You cannot convert a string and a Boolean object to an Integer object.


Java record -44-object Array traps

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.