How to store arrayList into an array in java?
7 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:
4 Comments
Paŭlo Ebermann
Better define the
arrOfLists as List<String>[], or maybe List<?>[].Sean Patrick Floyd
@Paŭlo I know, but
List<String>[] is a syntax error and List<?> is not a huge gain :-)Paŭlo Ebermann
Ah, right, I forgot the stupid non-generic arrays ... At least,
List<?>[] gives no warnings for using the raw type.Sean Patrick Floyd
@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 :-)
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
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
Sean Patrick Floyd
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 Expressionmaerics
@Sean: right, I just threw that in there for demonstration, I'll update the answer to make it clear...