How does this assignment operation work..?
I came across something new which i really found hard to understand.. Here is what i have done and it works perfectly fine..
Vector<String[]> v = new Vector<String[]>();
v.add(s);
String[][] s1 = new String[v.size][]
v.toArray(s1);
my question is how does it work even though method toArray() takes only 1-D array as argument..? I'm not muc开发者_高级运维h old for java programming so seeking an explanation..
Thanks in advance..
There are only really 1-D arrays in Java - where it looks like you've got a multi-dimensional array, it's actually just an array of arrays.
So if we ignore the fact that String[] itself is an array, and replace it with StringArray
everywhere, we get this code:
Vector<StringArray> v = new Vector<StringArray>();
v.add(s);
StringArray[] s1 = new StringArray[v.size()];
v.toArray(s1);
Now that doesn't look so odd, right? s1
is an array of string arrays, and v
is a vector of string arrays. v.toArray()
takes an array of string arrays as a parameter, so we can use s1
as the argument.
It's simple: v
is a vector of 1-D arrays, toArray
returns a 1-D array of whatever elements in the vector are (in this case 1-D arrays). The result is a 1-D array of 1-D arrays, more commonly known as a 2-D array.
toArray() accepts a 1-D array of objects.
A string array is an object.
s1 is an array of string arrays.
QED
The argument is treating "String[][]" as a "1-dimensional array" of the "String[]" objects.
In this case, Vector.toArray(T[] a) takes an array of T's. Let's replace the generic T with the type "String[]" (note that a String[] is an object). So this means Vector.toArray(String[][] a) takes String[][] as an argument.
精彩评论