3

When I'm creating an array of objects, how can I add the argument for the constructor inside each object? Like this:

foos = new Foo[10];

How do I make 10 objects with their constructors? I do not understand where do I put the arguments that is passed to the constructors of every object?

JonLunde
  • 151
  • 1
  • 3
  • 10
  • 2
    you just defined the array, now you need to loop over it and initialize each element as `foos[i] = new Foo(...)`. – SomeJavaGuy Apr 20 '16 at 09:36

6 Answers6

6
foos = new Foo[10];

creates an array that can hold references to 10 Foo instances. However, all the references are initialized to null.

You must call the constructor for each element of the array separately, at which point you can specify whatever argument you wish :

foos[0] = new Foo (...whatever arguments the constructor requires...);
...
Eran
  • 387,369
  • 54
  • 702
  • 768
3

This is just the allocation for a new array object of type Foo to hold multiple elements. In order to create and store actual object you will do something like this:

foos[0]=new Foo(); //Call constructor here
.
.
.
foos[10]= new Foo(); //Call constructor here
Sanjeev
  • 9,876
  • 2
  • 22
  • 33
2
foos = new Foo[10];

This is create an array type Foo, this is not creating object

for Initializing do following:

for(int i=0;i<foos.length; i++){
   foos[i] =  new Foo (your-argument);
}

See Arrays for more details

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
2

You can do it inline like so:

Foo[] foos = new Foo[] {
                  new Foo(1),
                  new Foo(2),
                  new Foo(10)
               };

Or like so:

Foo[] foos = {
                new Foo(1),
                new Foo(2),
                new Foo(10)
             };
weston
  • 54,145
  • 21
  • 145
  • 203
1

let's say that Foo take a String as an argument so the constructor for Foo is something like this:

public Foo(String arg){
this.arg = arg;
}

if arguments you need to pass to the constructors are different from each other, so you will need to use separate initialization for every element. as @Sanjeev mentioned but with passing an argument.

foos[0]=new Foo(argOne);
.
.
foos[10]= new Foo(argTen);

on the other hand if your arguments are related to to an array index, you should use loop as @Sumit mentioned

for(int i=0;i<foos.length; i++){
   foos[i] =  new Foo (arg + i);
}
Mohamed Ibrahim
  • 3,714
  • 2
  • 22
  • 44
0

So in order to create "10" new objects you need to create the array to hold the objects and then loop over the list while adding a new object to each index of the array.

int foosSize = 10;
Foo[] foos = new foos[foosSize];

for(int i = 0; i < foosSize; i++) {
    foos[i] = new Foo();
}

this will create a new foo object and add it to the index in the array you have created.

Sean Keane
  • 108
  • 1
  • 8