1
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.

1
  • i think err is you have un object for size . use alist.size(). plus api method is there see Stendika's answer Commented Jan 1, 2014 at 14:46

5 Answers 5

3

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?

Sign up to request clarification or add additional context in comments.

1 Comment

@ZouZou Indeed. Thanks, fixed the link :)
1

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++)

Comments

1

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.