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!

Bradley
  • 1,234
  • 1
  • 12
  • 24
  • No, you can't. But look at the `Arrays` class for alternatives. – Sotirios Delimanolis Mar 05 '14 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. – dev Mar 05 '14 at 16:08

3 Answers3

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));
Rainbolt
  • 3,542
  • 1
  • 20
  • 44
  • 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. – Bob Stout Mar 05 '14 at 16:17
  • @BobStout You can't think of a use for an array of 30 identical objects? You aren't very imaginative. – Rainbolt Mar 05 '14 at 16:18
  • I mainly deal with thousands of objects, all different, all interrelated. My imagination is currently occupied. :) – Bob Stout Mar 05 '14 at 16:20
  • 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! – Bradley Mar 05 '14 at 16:26
0

You could do something like this:

theArray = {20, 20, 20};

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

Salah
  • 8,567
  • 3
  • 26
  • 43
-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;
}
Bob Stout
  • 1,237
  • 1
  • 13
  • 26
  • 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. – Bradley Mar 05 '14 at 16:21
  • John's answer is best for you then. Check out odys's answer at http://stackoverflow.com/questions/9128737/fastest-way-to-set-all-values-of-an-array – Bob Stout Mar 05 '14 at 16:25
  • If you're going to downvote the answer, at least be a man and explain why. – Bob Stout Mar 06 '14 at 21:50