Reputation: 449
How to store arrayList into an array in java?
Upvotes: 6
Views: 53828
Reputation: 156434
Try the generic method List.toArray()
:
List<String> list = Arrays.asList("Foo", "Bar", "Gah");
String array[] = list.toArray(new String[list.size()]);
// array = ["Foo", "Bar", "Gah"]
Upvotes: 0
Reputation: 298898
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:
Upvotes: 15
Reputation: 14159
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();
Upvotes: 3
Reputation: 816404
You mean you want to convert an ArrayList
to an array?
Object[] array = new Object[list.size()];
array = list.toArray(array);
Choose the appropriate class.
Upvotes: 2
Reputation: 13666
List list = new ArrayList();
list.add("Blobbo");
list.add("Cracked");
list.add("Dumbo");
// Convert a collection to Object[], which can store objects
Object[] ol = list.toArray();
Upvotes: 0
Reputation: 8900
List<Foo> fooList = new ArrayList<Foo>();
Foo[] fooArray = fooList.toArray(new Foo[0]);
Upvotes: 0
Reputation: 64632
List list = getList();
Object[] array = new Object[list.size()];
for (int i = 0; i < list.size(); i++)
{
array[i] = list.get(i);
}
Or just use List#toArray()
Upvotes: 0