0

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.

3
  • What language is this? c++? java? Commented Apr 12, 2012 at 9:14
  • Yea, sorry, just noted. its Java. Commented Apr 12, 2012 at 9:19
  • Welcome to Stack Overflow. To ensure your questions are viewed by as many people as possible ensure you tag your question with the programming language (I'll do this now). Commented Apr 12, 2012 at 9:21

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thx man. you just saved my day. Works like a charm now. dont know why i wanted my loop the other way :) I dont know how, but if i can Rep you i will.
You probably can't upvote but you just accept the answer (click the tick beside the answer) after 10 mins. But only click it if it solved the problem and was the most useful answer. Wait and see if others post something more useful.
1
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. :)

1 Comment

again, thanks. iv chosen to accept this answer as it is more dirrect, and tells me some thing about # to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.