SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Rob Spoor wrote:The proper way to create a List (or any Collection) into an array is to use the other toArray method, and to use generics properly:
Rob Spoor wrote:
If you want to still use a List<Object>, you will need to iterate manually. I see two ways:
1) Create a List<String> to which you first add all String elements, then convert that into a String as shown above
2) Create a String[] as large as the List. Then add all String elements, using a counter variable. Afterwards, if the counter is less than the array size, use Arrays.copyOf to trim the array.
Sudhir Srinivasan wrote:
In other words - if I've understood your response correctly - String[] is an Object[] and not the other way.
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
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.
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.
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.