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?

6
  • Not with a primitive array, no. Commented May 4, 2017 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. Commented May 4, 2017 at 11:12
  • Isn't the same in 'C', you will need to initialise those value at some point too (might be rusty) Commented May 4, 2017 at 11:15
  • 1
    That's confirming one thing, my C is rusty ! Thanks @Michael . Commented May 4, 2017 at 11:19
  • 1
    @Michael I am the one that mispelled ;) hard to use a constructor in C indeed ;) Commented May 4, 2017 at 11:28

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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());

1 Comment

I think it's pretty clear he doesn't want the second one.

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.