0

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.

4 Answers 4

3
 Foo[] myArray = myList.toArray(new Foo[myList.size()]);
Sign up to request clarification or add additional context in comments.

2 Comments

myList.toArray(new Foo[0]) is enough
Of course it is enough. But with it empty array will be created, tested that it doesn't fit and than created another array that fits. What for this empty array? To reduce amount of code in non performance-critical places?
1

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()]);

1 Comment

by matrix I meant vector, sorry
1
Foo[] myArray = (Foo[])myList.toArray(new Foo[myList.size()]);

Comments

1

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]);  

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.