简体   繁体   中英

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). If you have an array of size N , the indexes will be from [0, N-1] (Total size of N ).

i <= alist .size() 

should be

i < alist .size()
   ↑
 No "=" 

Why don't you simply use toArray ?

You are very close. Your for loop condition says to loop as long as i is less than or equal to 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.

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]) . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM