Initalizing a class in a loop

Dear All,
I have class with the constructor that uses some input parameters (for example two integers). I determine the constructor parameters within the loop. My question is:
1) Should I put the constructor in the loop; or
2) I should create array list so that every time the new parameters are determined within the loop new class well be instantiated:
Thank you
[380 byte] By [lontana] at [2007-11-20 11:22:36]
# 1 Re: Initalizing a class in a loop
You're going to have to clarify what you mean (e.g. provide some example code?).

When you call a constructor, you are instantiating the class. What has an array list got to do with it?

Judge a man by his questions, rather than his answers...
Voltaire
dlorde at 2007-11-10 2:14:10 >
# 2 Re: Initalizing a class in a loop
for(int i=0; i<n; i++)
{
a= i*8-2;
b=i+9-a;
1) MyClass c= new MyClass(a,b);
or
2) MyClass c[i]=new MyClass(a,b);
}
lontana at 2007-11-10 2:15:10 >
# 3 Re: Initalizing a class in a loop
Option 2, MyClass c[i]=new MyClass(a,b); isn't valid Java. You could have c[i]=new MyClass(a,b); where 'c' is an array of MyClass declared elsewhere.

The answer to your question depends on what you're trying to do. If you want to create a new instance of MyClass each time round the loop for use within the loop only, use the first option. If you want to fill an array with MyClass instances that you can use outside the loop, use option 2.

If you declare the MyClass variable inside the loop (option 1), its scope will be limited to inside the loop, which means you can only use it within the loop, and each time round, you'll get a new variable in place of the previous one. Remember that the scope of any variable is limited to the closest set of enclosing curly braces {}.

If you declare an array of MyClass outside the loop and put a new instance into it every time round the loop (option 2), you end up with an array full of instances of MyClass, which you can use outside the loop because the array was declared outside the loop.

The two options are completely different.

The most important single aspect of software development is to be clear about what you are trying to build...
B. Stroustrup
dlorde at 2007-11-10 2:16:09 >