Rob Spoor wrote:]Almost correct. str1 is already a String[]. You're copying that into a new String[] of exactly the same size. You need to use a different value instead of str1.length. Also, because str1 is already a String[], you can omit the String[].class.
You are right. str1 being the original array, to be copied into another String[] str2
of the same size as str1.
Use for...loop to convert each element of str1 toString and
finally,
Rob Spoor wrote:The third argument is only necessary in the following scenario:
- You have a reference of type X[] (e.g. X[] == Object[]).
- You know that every element is actually an instance of type Y, with Y extends X (e.g. Y == String).
- You want to get an Y[] out of that.
Got it! I tried the same and it works. Here's how
Create an object array ob from the toArray method on a generic ArrayList (shown above)Contents of al2 to be dumped into the newly allocated object array whose size is identical to the size of al2for...loop to convert each element of the object array to String & store in ob andCreate String[] and use Arrays.copyOf method, by passing the third argument, to get String[] from ob
and the output
Rob Spoor wrote:If you have an X[] and want to get another X[] (e.g. String[] -> String[]), the third argument can be omitted. copyOf will then use the actual class of the first argument (String[]) to create the copy.
I'm intrigued by the String[].class and here's my (wild) guess on its working:
- Define the Array class (being entity class) having a property, say
obj, of
java type String
- Generate getters and setters within this class to populate and return the String value
- String class (being component class to Array) has property, say
data, of type char[]
- String class mapped to STRING table with unique ID (being primary key, foreign key in CHAR table) assigned to each object
obj
- Each char in turn converted to charset and/or bytes understood by jvm and stored in corresponding CHAR table
- From this internal representation, java retrieves & returns (thru getters) the Class, in this case the String[].class
Again, its a wild guess and so kindly excuse me if its a load of gibberish.
Could you please, therefore, explain its working briefly and suggest any link - that deals with how the Class object of an Array (be it of type int, char, String etc.) is obtained - as reference.
Many thanks,
Sudhir