File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Problem adding in ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem adding in ArrayList" Watch "Problem adding in ArrayList" New topic
Author

Problem adding in ArrayList

Martin Lira
Ranch Hand

Joined: May 26, 2004
Posts: 97
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
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15300
    
    6

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.


GenRocket - Experts at Building Test Data
Martin Lira
Ranch Hand

Joined: May 26, 2004
Posts: 97
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem adding in ArrayList