I have some doubts/questions regarding the object creation. I have heard that
objects should not be created in the loop. Whats wrong with the creation of
objects inside the loop? Whats the difference between creating outside the loop
and creating inside the loop?
Please consider the following example.
public java.util.List<Object> objectCreationTest(){
java.util.List<Object> objectList =new java.util. ArrayList<Object>();
Object obj = null;
for(int i = 0 ; i <1000;i++){
Object e = new Object(); //1 --> Is this object creation wrong?
obj = new Object(); //2 --> Is this right way to create?
objectList.add(e );
}
return objectList ;
}
Please suggest me which way I have to follow?
There’s nothing wrong with creating objects in a loop. Sometimes it’s the only way to create a number of (related) objects.
In your example, you can simply do: