5

Is there a way to define a default value for an object in array to be initialized with?

In the same way that primitive types are initialized when declaring an array of them:

int[] myIntArray = new int[5]; // we now have an array of 5 zeroes
char[] myCharArray = new char[2]; // an array in which all members are "\u0000"

etc.

I'd like to declare an array of objects of a type that I've defined, and have them automatically initialize in a similar fashion. I suppose this would mean I'd like to run new myObject() for each index in the array (with the default constructor).

I haven't been able to find anything relevant online, the closest I got was to use Arrays.fill(myArray, new MyObject()) after initializing the array (which actually just creates one object and fills the array with pointers to it), or just using a loop to go over the array and initialize each cell.

thank you!

EDIT: I realized this is relevant not just to arrays, but for declaring objects in general and having them default to a value / initialize automatically.

6
  • 1
    This behavior is well define in the JLS. Commented Mar 30, 2016 at 14:52
  • 3
    There's no built in solution, not in the same way that Java will zero out an array for you when it's allocated. A fairly nice solution is this: Stream.generate(() -> new MyObject()).limit(5).toArray(MyObject[]::new) Commented Mar 30, 2016 at 14:59
  • could you elaborate on what this does exactly? thanks! Commented Mar 30, 2016 at 15:04
  • @Cardano You should make this an answer. Commented Mar 30, 2016 at 15:05
  • @Cardano That's brilliant using a Java 8's feature. Commented Mar 30, 2016 at 15:08

6 Answers 6

9

The Java 8 way:

MyObject[] arr = Stream.generate(() -> new MyObject())
    .limit(5)
    .toArray(MyObject[]::new);

This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.

If you wanted to set some properties on the object or something, you could have a more involved supplier:

() -> {
  MyObject result = new MyObject();
  result.setName("foo");
  return result;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Do this so you can initialize the array when declaring it:

int[] myIntArray =  {0, 0, 0,0,0};
char[] myCharArray = { 'x', 'p' };

you could of course do:

int[] myIntArray = new int[5]; 

and the in a for loop set all indexes to the initial value... but this can take a while if the array is bigger...

Edit:

for custom objects is the same just use an anonymous constructor in the init

Example:

public class SOFPointClass {

private int x;
private int y;

    public SOFPointClass(int x, int y) {
    this.x = x;
    this.y = y;
}

    // test
    public static void main(String[] args) {
        SOFPointClass[] pointsArray = { new SOFPointClass(0,0) ,  new SOFPointClass(1,1)};
    }
}

4 Comments

I don't think it's what he wants. He's talking about objects.
I am indeed talking about objects. I gave the int and char arrays as examples of what happens with primitive types, which is what I want to do with an object. (And I'm a woman. just saying :))
Ohhh, I get it now, please take a look at the update in the answer with the SOFPointClass
@HadasJacobi Sorry about the 'He'. :)
1

You can use Arrays.setAll since Java 8:

var arr = new MyObject[5];
Arrays.setAll(arr, i -> new MyObject());

Comments

0

I don't see a way that Java provides to do this.

My suggestion would be define a function to do it.

Object[] initialize(Class aClass, int number) throws IllegalAccessException, InstantiationException {
    Object[] result = new Object[number];
    for (int i = 0; i < number; ++i) {
        result[i] = aClass.newInstance();
    }
}

Then call it as Object[] arr = initialize(YourClass.class, 10)

Comments

0

In Java, the array is initialized with the default value of the type. For example, int default is 0. The default value for cells of an array of objects is null as the array cells only hold references to the memory slot contains the object itself. The default reference points to null. In order to fill it with another default value, you have to call Arrays.fill() as you mentioned.

Object[] arr=new Object[2];
Arrays.fill(arr, new Object());

2 Comments

thanks, but as I've mentioned, as far as my tests have shown this fills the array with pointers to the same new object, which is not useful (at least in this case...)
Ok, I got what you need .. so either a loop or in Java 8 use stream way explained above
0

As far as I know there is no way of doing what you want with just plain java (that is to say there may be an external library I don't know about).

I would take the hit and loop over the array. Something like this should work:

myObject[] array = new myObject[5];

for (int i = 0; i < array.length; i++) {
    array[i] = new myObject();
}

You could also shorten this using lambdas, like Cardano mentioned in his answer.

Comments

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.