• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!