aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collection.toArray() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collection.toArray() method" Watch "Collection.toArray() method" New topic
Author

Collection.toArray() method

Luis Torres
Greenhorn

Joined: May 02, 2008
Posts: 20
Hi.

I have this code:

public class Test3 {
public static void main(String [] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("one "); list.add("two "); list.add("three ");
String [] sa = new String[3];
sa = (String []) list.toArray(); // insert code here
for(String s : sa)
System.out.print(s);
}
}

If I run this class I get a ClassCastException.

Why?


SCJP5 90%
Mamadou Touré
Ranch Hand

Joined: Dec 27, 2007
Posts: 189
Hi luis,

What I understand, is : you cannot cast Object or array of Object to String or Array of String, I would suggest you to use the other toArray() method that takes an array as parameter and returns an array of the same type.

Here is your code with new change
Hi.

I have this code:

public class Test3 {
public static void main(String [] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("one "); list.add("two "); list.add("three ");
String [] sa = new String[3];
sa = list.toArray(sa); // insert code here
for(String s : sa)
System.out.print(s);
}
}


Hope this will help
[ May 06, 2008: Message edited by: Mamadou Tour� ]

SCJP 5 (76%)
SCWCD 5 (86%)
SCBCD 5(70%)
--------------------
"The greatest glory in living lies not in never falling, but in raising every time we fall.".. Nelson Mandela
Frank Hinkel
Greenhorn

Joined: Mar 28, 2008
Posts: 24
Hi Luis,
i would recommend to use it this way:
String[] sa = (String[]) list.toArray(new String[list.size()]);

You can delete "String [] sa = new String[3];" and it is more generic
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection.toArray() method
 
Similar Threads
String [] casting on toArray() necessary for this?
Why This Code Behaves in This Way
Generic type for Iterator is also required ?
toArray question
toArray() method