make arrayList.toArray() return more specific types
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
(available from java 11)
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()]);
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()];
list.toArray(customs);
for (Custom custom : customs) {
System.out.println(custom);
}
Here's my Custom
class:-
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}