6

How to store arrayList into an array in java?

2

7 Answers 7

15

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Better define the arrOfLists as List<String>[], or maybe List<?>[].
@Paŭlo I know, but List<String>[] is a syntax error and List<?> is not a huge gain :-)
Ah, right, I forgot the stupid non-generic arrays ... At least, List<?>[] gives no warnings for using the raw type.
@Paŭlo ok, added that change, but if you are crazy enough to store a list in an array you probably don't care about compiler warnings either :-)
3

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();

Comments

2

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.

Comments

0
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()

Comments

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

Comments

0
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();

Comments

0

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"]

2 Comments

The last line won't compile in Java (while it would be perfectly legal in Groovy). Javac says: Syntax error, insert "AssignmentOperator Expression" to complete Expression
@Sean: right, I just threw that in there for demonstration, I'll update the answer to make it clear...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.