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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With