• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubts in converting arraylists to array

 
sagar shiraguppi
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
sagar shiraguppi
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Fred, you cleared my doubts
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic