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
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?
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.