How to save arrayList to array in java?

How to save arrayList to array in java?

+4
source share
7 answers

It depends on what you want:

List<String> list = new ArrayList<String>(); // add items to the list 

Now, if you want to save the list in an array, you can do one of them:

 Object[] arrOfObjects = new Object[]{list}; List<?>[] arrOfLists = new List<?>[]{list}; 

But if you want list items in an array, do one of the following:

 Object[] arrayOfObjects = list.toArray(); String[] arrayOfStrings = list.toArray(new String[list.size()]); 

Reference:

+11
source

If the type is known (it is not a generics parameter) and you need an array of type:

 ArrayList<Type> list = ...; Type[] arr = list.toArray(new Type[list.size()]); 

Otherwise

 Object[] arr = list.toArray(); 
+4
source

Do you want to convert an ArrayList to an array?

 Object[] array = new Object[list.size()]; array = list.toArray(array); 

Select the appropriate class.

+2
source
 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 ()

0
source
 List<Foo> fooList = new ArrayList<Foo>(); Foo[] fooArray = fooList.toArray(new Foo[0]); 
0
source
 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(); 
0
source

Try the generic List.toArray() method:

 List<String> list = Arrays.asList("Foo", "Bar", "Gah"); String array[] = list.toArray(new String[list.size()]); // array = ["Foo", "Bar", "Gah"] 
0
source

Source: https://habr.com/ru/post/1342971/


All Articles