This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Collection.toArray() method  RSS feed

 
Luis Torres
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Mamadou Touré
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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� ]
 
Frank Hinkel
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!