Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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.

share|improve this question
    
i think err is you have un object for size . use alist.size(). plus api method is there see Stendika's answer –  tgkprog Jan 1 at 14:46

5 Answers 5

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?

share|improve this answer
    
@ZouZou Indeed. Thanks, fixed the link :) –  Maroun Maroun Jan 1 at 14:26

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++)
share|improve this answer

All you really need is to say is them = alist.toArray(new Student[them.length]). This will simply copy the data over.

share|improve this answer
ArrayList<Student> alist = new ArrayList();
// object type is student
//arraylist contains student objects        
Student[] arr= new Student[un.size()];
alist.toArray(arr);
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.