user594720
user594720

Reputation: 449

How to store arrayList into an array in java?

How to store arrayList into an array in java?

Upvotes: 6

Views: 53828

Answers (7)

maerics
maerics

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

Sean Patrick Floyd
Sean Patrick Floyd

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

Axel
Axel

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

Felix Kling
Felix Kling

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

Umesh Kacha
Umesh Kacha

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

Adam Ayres
Adam Ayres

Reputation: 8900

List<Foo> fooList = new ArrayList<Foo>();
Foo[] fooArray = fooList.toArray(new Foo[0]);

Upvotes: 0

Boris Pavlović
Boris Pavlović

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

Related Questions