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[]
?
Like this:
List<String> list = new ArrayList<>();
String[] a = list.toArray(new String[0]);
Before Java 6 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 Java 6 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 list = new ArrayList<String>();
String[] a = ((List<String>) list).toArray(new String[list.size()]);