0

I have an array of Object and wondered if I could pass parameters whilst simultaneously instantiating the array.

For example:

theArray = new Object(20, 20, 20)[30];

I want to avoid looping through each element and passing parameters to them after the array has been created if I can help it.

I know the above syntax isn't correct, but it illustrates what I'm trying to achieve.

Thanks for your responses!

2
  • No, you can't. But look at the Arrays class for alternatives. Commented Mar 5, 2014 at 16:08
  • You might be able to dosomething like theArray = {new Object(20, 20, 20), new Object(20, 20, 20)...} but would still have to type them all out. Not entirely sure this would work, but worth a shot. Commented Mar 5, 2014 at 16:08

3 Answers 3

2

Use Arrays.fill() to avoid looping.

Example

Create an array with 30 instances of MyClass that all have the values 20, 20, 20.

MyClass[] theArray = new MyClass[30];
Arrays.fill(theArray, new MyClass(20,20,20));
Sign up to request clarification or add additional context in comments.

4 Comments

Nice...didn't know about that. Can't think of a use for it for what I'm doing, but it's good to know if the need arises.
@BobStout You can't think of a use for an array of 30 identical objects? You aren't very imaginative.
I mainly deal with thousands of objects, all different, all interrelated. My imagination is currently occupied. :)
This is almost what I'm looking for. I guess it's a lack in my understanding of the task at hand. This will provide all the objects in the array with the same properties. However I need them all to have the same properties, with a few exceptions. So I guess I will have to loop!
0

You could do something like this:

theArray = {20, 20, 20};

This means that you have an array with size of 3.

Comments

-1

If you're just trying to keep your main code clean, shuffle it off to a function:

theArray = getObjects(30);
...
private Object[] getObjects(int numObjects){
    Object[] returnObjects = new Object[30];
    for(int x=0; x<numObjects;x++){
    //etc, etc, etc
    }
    return returnObjects;
}

3 Comments

It's more about performance, I don't want to have to loop through each element in the array and pass parameters to them if I can just do that at the point where I instantiate the array.
John's answer is best for you then. Check out odys's answer at stackoverflow.com/questions/9128737/…
If you're going to downvote the answer, at least be a man and explain why.

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.