[英]How to store arrayList into an array in java?
如何将arrayList存储到Java中的数组中?
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: 参考:
If Type is known (aka not a generics parameter) and you want an Array of Type: 如果Type是已知的(又不是泛型参数),并且您需要Type数组:
ArrayList<Type> list = ...;
Type[] arr = list.toArray(new Type[list.size()]);
Otherwise 除此以外
Object[] arr = list.toArray();
You mean you want to convert an ArrayList
to an array? 您的意思是您想将
ArrayList
转换为数组吗?
Object[] array = new Object[list.size()];
array = list.toArray(array);
Choose the appropriate class. 选择适当的课程。
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() 或者只是使用List#toArray()
List<Foo> fooList = new ArrayList<Foo>();
Foo[] fooArray = fooList.toArray(new Foo[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();
Try the generic method List.toArray()
: 尝试使用通用方法
List.toArray()
:
List<String> list = Arrays.asList("Foo", "Bar", "Gah");
String array[] = list.toArray(new String[list.size()]);
// array = ["Foo", "Bar", "Gah"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.