How to store arrayList into an array in java?
Now if you want to store the list in an array, you can do one of these: Object[] arrOfObjects = new Object[]{list}; List<?>[] arrOfLists = new List<?>[]{list}; But if you want the list items in an array, do one of these: Object[] arrayOfObjects = list.
The ArrayList class is a Java class that you can use to store lists of objects. You can also store objects in an array, but arrays have a couple of obvious problems. To create an array, you have to specify a size for the array.
That depends on what you want:
List<String> list = new ArrayList<String>();
// add items to the list
Now if you want to store the list in an array, you can do one of these:
Object[] arrOfObjects = new Object[]{list};
List<?>[] arrOfLists = new List<?>[]{list};
But if you want the list items in an array, do one of these:
Object[] arrayOfObjects = list.toArray();
String[] arrayOfStrings = list.toArray(new String[list.size()]);
Reference:
Collection.toArray()
Collection.toArray(T[])
If Type is known (aka not a generics parameter) and you want an Array of Type:
ArrayList<Type> list = ...;
Type[] arr = list.toArray(new Type[list.size()]);
Otherwise
Object[] arr = list.toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With