Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confused ,why Object[] objs (type of objs[i] is int[]) cant cast into int[][]

list.toArray() returns Object[] and it contains only int[]. So i thought i can cast it directly into int[][]. But actually i was wrong,it will lead to a cast exception.

list.toArray(new int[list.size()][]);

it's ok this way,but i'm still confused.

List<int[]> list = new ArrayList<>();
//some code

//cast exception
return (int[][])list.toArray();
//this way is ok
return list.toArray(new int[list.size()][]);

Why does it throw that exception?

like image 801
wqbill Avatar asked May 10 '19 09:05

wqbill


1 Answers

Here:

//cast exception
return (int[][])list.toArray();

Due to type erasure, this one creates an actual array of Object. An array of Objects is not an array of int arrays, thus you can't cast it. A box for eggs doesn't turn into a bottle for milk just because you scream "behold, become a bottle" at it.

To make that really clear: the above call doesn't know the exact type to use, so it has to resort to that basic default Object[]. And because int[] is of type Object, that list method can then store these arrays into the result array. An array of objects, and each object is an array of int.

But here:

return list.toArray(new int[list.size()][]);

You explicitly say that the array returned should be of type int[][]. Thus, at runtime, the body of that method knows that it should return that type.

And just for the record: you might prefer

return list.toArray(new int[0][]);

Providing an "already sized" array is a relict from earlier times, in general, in 2019, you prefer passing an empty array.

like image 120
GhostCat Avatar answered Oct 17 '22 07:10

GhostCat