Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String [] casting on toArray() necessary for this? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String [] casting on toArray() necessary for this?" Watch "String [] casting on toArray() necessary for this?" New topic
Author

String [] casting on toArray() necessary for this?

Firas Zuriekat
Ranch Hand

Joined: May 09, 2006
Posts: 143
1. import java.util.*;
2. class MyList {
3. public static void main(String [] args) {
4. LinkedList<String> list = new LinkedList<String>();
5. list.add("one "); list.add("two "); list.add("three ");
6. String [] sa = new String[3];
7. // insert code here
8. for(String s : sa)
9. System.out.print(s);
10. }
11. }


Which, inserted at line 7, allows the code to compile and run without exception?

A) sa = (String []) list.toArray();
B) sa = (Object []) list.toArray();
C) sa = list.toArray(sa);

Answer C.

Why is A and B wrong. For B, Couldn't the Object[] or String[] cast be used. Is it because using the syntac String [] as a valid cast wrong?

Can I use sa = (String []) list.toArray(new String[0]) or just (String []) list.toArray(new String[0])??
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
A) sa = (String []) list.toArray(); //list.toArray() returns Object[] and can not cast to String[]


B) sa = (Object []) list.toArray(); //sa is defined as String[]

C) sa = list.toArray(sa); // It returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
Firas Zuriekat
Ranch Hand

Joined: May 09, 2006
Posts: 143
Ok, thanks...

I alo think sa = list.toArray(new String[0]) would work at runtime. Although "sa" is not exactly the same as the parameneter, the type is at least specified from the parameter.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String [] casting on toArray() necessary for this?
 
Similar Threads
array length 0
Collection.toArray() method
toArray question
toArray() method
getting the value of string array out of object array