File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes doubts in converting arraylists to array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "doubts in converting arraylists to array" Watch "doubts in converting arraylists to array" New topic

doubts in converting arraylists to array

sagar shiraguppi
Ranch Hand

Joined: Jul 16, 2007
Posts: 74
hi guys, I am converting arraylist into array..
Please let me know what exactly is happening in the line which is in italic and bold. Other lines of code I understood, please anyone explain me what exactly that particular line of code is doing..
code is as follows

ArrayList arl = new ArrayList();

// Add elements to the array list
arl.add(new Integer(1));
arl.add(new Integer(2));
arl.add(new Integer(3));
arl.add(new Integer(4));

System.out.println("Contents of al: " + arl);

// get array
Object ia[] = arl.toArray();
int sum = 0;

// sum the array
for (int i = 0; i < ia.length; i++) {
sum += ((Integer) ia[i]).intValue();
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11923

ia is an array of objects.

ia[i] gets you the i'th element in that array.

(Integer) ia[i]) casts that object reference to an Integer.

((Integer) ia[i]).intValue() gets you the int value of the Integer.

sum += ((Integer) ia[i]).intValue(); adds the int value to whatever is currently in sum.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
sagar shiraguppi
Ranch Hand

Joined: Jul 16, 2007
Posts: 74
Thank you Fred, you cleared my doubts
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

You don't even need the array use can just use to ArrayList to iterate through it. And if you use a generic ArrayList then it's even easier.

If you do need the array for omitted reasons then use: Integer[] array = list.toArray(new Integer[list.size()]); Because then you don't need to cast.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
I agree. Here's the link:
subject: doubts in converting arraylists to array
It's not a secret anymore!