Reputation: 539
I'm working in java.
I have an ArrayList<foo> myList
and i try to convert it into an array.
Foo[] myArray = (Foo[])myList.toArray();
In eclipse i'm getting the error object cannot be cast to foo.
Any solutions? I'm trying to use a dynamic allocated matrix an an ArrayList
is not sufficient because i have to apply some sorts.
Upvotes: 0
Views: 937
Reputation: 2019
I hope this might help.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> myList = new ArrayList<String>();
String s="hello";
String r="world";
myList.add(s);
myList.add(r);
String[] newList = myList.toArray(new String[0]);
System.out.println(newList[0]+" "+newList[1]);
}
}
Upvotes: 1
Reputation: 49
Foo[] myArray = (Foo[])myList.toArray(new Foo[myList.size()]);
Upvotes: 1
Reputation: 81684
I don't know what you mean by matrix, which is often used to mean a two-dimensional array, but putting that aside: if you just call toArray()
like this, with no arguments, the returned array won't be a Foo[]
, it'll be an Object[]
containing your Foo
objects. You need to use the other version of toArray()
, the one that lets you supply your own array object, like this:
Foo[] myArray = myList.toArray(new Foo[myList.size()]);
Upvotes: 1