tgm_rr
tgm_rr

Reputation: 539

Java dynamic matrix from Array List

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

Answers (4)

Sreenath Nannat
Sreenath Nannat

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

Foo[] myArray = (Foo[])myList.toArray(new Foo[myList.size()]);

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

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

Ivan Sopov
Ivan Sopov

Reputation: 2370

 Foo[] myArray = myList.toArray(new Foo[myList.size()]);

Upvotes: 3

Related Questions