[英]How to create an array from an arraylist
ArrayList<Student> alist = new ArrayList();
// object type is student
//arraylist contains student objects
Student[] arr= new Student[un.size()];
for(int i = 0; i <= alist .size(); i++){
them[i] = arr.get(i);
}
What I want to do is to create an array of students without getting the array out of bounds exception. 我想做的是创建一个学生数组,而不会使数组超出范围。
Arrays are zero-based in Java (and most languages). 数组在Java(和大多数语言)中从零开始 。 If you have an array of size N
, the indexes will be from [0, N-1] (Total size of N
). 如果你有大小的数组N
,索引将是从[0,N-1](总的大小N
)。
i <= alist .size()
should be 应该
i < alist .size()
↑
No "="
You are very close. 你很亲密 Your for loop condition says to loop as long as i
is less than or equal to alist.size()
. 您的for循环条件表示只要i
小于或等于alist.size()
就会alist.size()
。 If you do that, you'll always run one over. 如果这样做,您总是会一遍又一遍。
For example, if you only have one item in alist
, your size will be 1, but you really only want to loop until 0. 例如,如果alist
只有一项,则大小将为1,但实际上您只想循环到0。
Change this: 更改此:
for(int i = 0; i <= alist.size() ; i++)
To this: 对此:
for(int i = 0; i < alist.size() ; i++)
All you really need is to say is them = alist.toArray(new Student[them.length])
. 您真正需要说的是them = alist.toArray(new Student[them.length])
。 This will simply copy the data over. 这将简单地复制数据。
ArrayList<Student> alist = new ArrayList();
// object type is student
//arraylist contains student objects
Student[] arr= new Student[un.size()];
alist.toArray(arr);
You can try like this also, All above ans are correct but this is simple and easy 您也可以这样尝试,以上所有答案都是正确的,但这很简单
String[] arr = alist.toArray(new Student[un.size()]);
list.toArray return an array containing all of the elements in this collection
list.toArray return an array containing all of the elements in this collection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.