Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store arrayList into an array in java?

How to store arrayList into an array in java?

like image 531
user594720 Avatar asked Mar 09 '11 10:03

user594720


People also ask

How do I store a list in an ArrayList?

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.

Can ArrayList hold array?

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.


2 Answers

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[])
like image 52
Sean Patrick Floyd Avatar answered Oct 26 '22 22:10

Sean Patrick Floyd


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();
like image 31
Axel Avatar answered Oct 26 '22 22:10

Axel