ClassCastException for multidimensional arrays in Java

I was trying to understand the logic behind the execution of the following block of code:

Integer[][] mdArray = new Integer[][] { { 1, 2 }, { 3, 4 }, { 5, 6 },
        { 7, 8 } };

List<Integer[]> mdArrayList = new ArrayList<Integer[]>();

// Iterate through every row of mdArray
for (Integer[] obj : mdArray) {
    mdArrayList.add(obj);
}

/* Throws ClassCastException because it cannot resolve the final array size?
 * 
 * i.e. it is a proper RTError.
 * 
 */
Integer[][] toArray = (Integer[][]) (mdArrayList.toArray());

      

The above code compiles fine, but when the final line is executed, throws a ClassCastException at runtime. My understanding is that the JVM cannot execute this code at runtime because even though toArray () is pushing an array of elements into the mdArrayList, the destination type cannot be resolved or promoted?

Any explanation would be appreciated! I'm just trying to figure out whether this kind of code execution should be avoided or exception handling should be avoided in order to output something more appropriate to the user's needs.

+3


source to share


2 answers


You don't have to quit. Transfer Integer[][]

to toArray

. Something like

Integer[][] toArray = mdArrayList.toArray(new Integer[][] {});
System.out.println(Arrays.deepToString(toArray));

      



Output

[[1, 2], [3, 4], [5, 6], [7, 8]]

      

+4


source


Try

Integer[][] toArray = mdArrayList.toArray(new Integer[mdArrayList.size()][]);

      



If you don't provide an argument to a method toArray

, the return type will always be Object[]

regardless of the actual type of what's inside the list.

If you provide an argument, you can either select it as a zero-length array ( new Integer[0][]

), in which case the method toArray

will create a new array of the same type; or you can provide an array if the size is correct and then the method toArray

will use that array. The latter is slightly more effective than the former, but not something you need to worry about a lot.

+2


source







All Articles