• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

doubts in converting arraylists to array

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
 
lowercase baba
Posts: 13091
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Fred, you cleared my doubts
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
I've read about this kind of thing at the checkout counter. That's where I met this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic