0

I'm in the process of porting some C++ code to Java.

Here's a snippet of my code:

class Foo{

...

private class Bar
{
    public byte[] data;
    public int    len;

    Bar() {
        data = new byte[256];
        len  = 0;
    }
}

... 

private Bar[] myArray = new Bar[10];

I want to have an array of 10 objects. But when I want to use the array further in my code, I notice that all 10 members are 'null'.

As a workaround I can solve it with a for-loop in the constructor of the primary class:

Foo() {
    for( int i=0; i<myArray.length; i++ )
        myArray[i] = new Bar();
}

Is there a better way to call the 10 constructors at once, without the need for a for-loop?

Hneel
  • 95
  • 10
  • Not with a primitive array, no. – Michael May 04 '17 at 11:11
  • No, you need to call the constructors one by one. The only other thing might be deserialization but that too would effectively need some kind of loop and well as properly serialized data. – Thomas May 04 '17 at 11:12
  • Isn't the same in 'C', you will need to initialise those value at some point too (might be rusty) – AxelH May 04 '17 at 11:15
  • @AxelH Not in C++ (which is what he's using). [It uses the default constructor](http://stackoverflow.com/questions/3575458/does-new-call-default-constructor-in-c) – Michael May 04 '17 at 11:17
  • 1
    That's confirming one thing, my C is rusty ! Thanks @Michael . – AxelH May 04 '17 at 11:19
  • 1
    @Michael I am the one that mispelled ;) hard to use a constructor in C indeed ;) – AxelH May 04 '17 at 11:28

2 Answers2

1

You'll need some for-loop equivalent in order for each index of the array to refer to a unique object.

For example:

IntStream.range(0,myArray.length).forEach(i->myArray[i] = new Bar());

Otherwise, if you don't mind all indices of the array to refer to the same object:

Arrays.fill(myArray, new Bar());
Eran
  • 387,369
  • 54
  • 702
  • 768
1

If you were prepared to use an implementation of the List interface, you could do the following:

List<Bar> myArray = new ArrayList<>(Collections.nCopies(10, new Bar());
                                                     /* ^ number of copies */

But this is not possible with primitive arrays ([n] style)

Michael
  • 41,989
  • 11
  • 82
  • 128