Search code examples
javaarraysobjecttypesarraylist

make arrayList.toArray() return more specific types


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[]?


Solution

  • Like this:

    List<String> list = new ArrayList<String>();
    
    String[] a = list.toArray(new String[0]);
    

    Before Java6 it was recommended to write:

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

    because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

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