Take the 2-minute tour ×

So, normally ArrayList.toArray() would return a type of Object[]....but supposed it's an Arraylist of object Custom, how do I make toArray() to return a type of Custom[] rather than Object[]?

share|improve this question
There are 2 methods with the same name 'toArray()' in ArrayList. Starting from 1.5, the second method takes typed array. Are you looking for solution for pre-1.5? –  Ritesh Feb 21 '11 at 2:33
See also bug 6260652. –  alexsmail Jan 19 '12 at 23:44
add comment

3 Answers

up vote 87 down vote accepted

Like this:


String[] a = list.toArray(new String[list.size()]);

It's tempting to do it like:

String[] a = list.toArray(new String[0]);

but the internal implementation will realloc a properly sized array anyway so you are better doing it upfront.

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);
share|improve this answer
AFAIK: This has something to do with Java as a whole, being unable to use generic constructors. So while it knows you need it to convert you an object like String[] or MyObject[], it cannot instantiate it on its own. –  David Is Not Here Apr 18 '13 at 20:23
java is the worst –  yano May 22 at 19:30
add comment

It doesn't really need to return Object[], for example:-

    List<Custom> list = new ArrayList<Custom>();
    list.add(new Custom(1));
    list.add(new Custom(2));

    Custom[] customs = new Custom[list.size()];

    for (Custom custom : customs) {

Here's my Custom class:-

public class Custom {
    private int i;

    public Custom(int i) {
        this.i = i;

    public String toString() {
        return String.valueOf(i);
share|improve this answer
add comment

Your Answer


