• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem adding in ArrayList

 
Martin Lira
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • 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
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic