开发者

How to store arrayList into an array in java?

开发者 https://www.devze.com 2023-02-16 04:50 出处:网络
How to store开发者_如何学Python arrayList into an array in java?That depends on what you want: List<String> list = new ArrayList<String>();

How to store开发者_如何学Python arrayList into an array in 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:

  • Collection.toArray()
  • Collection.toArray(T[])


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


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.


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<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<String> list = Arrays.asList("Foo", "Bar", "Gah");
String array[] = list.toArray(new String[list.size()]);
// array = ["Foo", "Bar", "Gah"]
0

精彩评论

暂无评论...
验证码 换一张
取 消