• 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Problem adding in ArrayList

 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Gurus,
Came across a small problem. Can anybody explain whats going on?
Here is my code:
void testList(){
ArrayList list = new ArrayList();
MyBean bean = new MyBean();

for(int i=0; i<10; i++){
bean.setXXXX(Integer.toString(i));
list.add(bean);
}
for(int i=0; i<list.size(); i++){
MyBean ref = (MyBean)list.get(i);
System.out.println("List value = "+ ref.getXXXX());
}
}
My problem is whenever i invoke the testList() method always the answer is 9. Should it not be 0,1,2,...9
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to move the MyBean declaration inside the first forloop.



Otherwise, you are setting the value of the same object each time and you need to be setting the value of a new object each time.
 
Martin Lira
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
Doesn't this mean you are unnecessarily creating 10 new instance of MyBean. Everytime you do a new MyBean() it will take lot of resources. What will happen if there are a couple of thousand iterations of the first for loop?

Thanks,
Martin
 
author and iconoclast
Posts: 24203
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suspect you'd benefit from reading this and this. If you read and understand these, I think you'd understand what's happening in your code, and be able to decide for yourself what to do here.
reply
    Bookmark Topic Watch Topic
  • New Topic