• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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])??
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic