Reputation: 41
Now, Im currently wrinting a simple graphics program. In it I hava a Array called m_ball.
Now, m_ball is suposed to contain up to 20 instances of the class Ball.
Rigth now I do this by the following code =
Ball m_activeBall0 = new Ball();
Ball m_activeBall1 = new Ball();
Ball m_activeBall2 = new Ball();
ect...
m_ball[1] = m_activeBall0;
m_ball[2] = m_activeBall1;
m_ball[3] = m_activeBall2;
ect...
Now thats all sound and well. But aint it posible to do it in a for loop. some thing like this =
for(int i = 0; i <m_ball.length;i++) {
Ball m_activeBall[i] = new Ball();
m_ball[i] = m_activeBall[i];
}
or have I lost it?
I simply cant seem to find a way to do this.
I tried Google, but cant seem to find the answer.
Oh.. yea. forgot to add. its Java.
Upvotes: 0
Views: 120
Reputation: 121971
You can use a for
loop,:
for (int i = 0; i < m_ball.length; i++)
{
m_activeBall[i] = new Ball();
m_ball[i] = m_activeBall[i];
}
Just to mention Arrays.copyOf()
. If m_activeBall
was created somewhere else you could make a copy of it:
Ball[] copy = Arrays.copyOf(m_activeBall, m_activeBall.length);
Upvotes: 2
Reputation: 3235
Ball[] m_ball = new Ball[20];
for(int i = 0; i < m_ball.Length; i++)
{
m_ball[i] = new Ball();
}
I wrote this in C# but I'm pretty much sure it's same with Java. Cheers. :)
Upvotes: 1