Hadas Jacobi
Hadas Jacobi

Reputation: 105

Initializing an object in an array with a default value - java

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.

Upvotes: 5

Views: 13405

Answers (6)

robinst
robinst

Reputation: 31417

You can use Arrays.setAll since Java 8:

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

Upvotes: 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)};
    }
}

Upvotes: 1

Cardano
Cardano

Reputation: 951

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;
}

Upvotes: 9

Tiz
Tiz

Reputation: 707

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.

Upvotes: 0

Mohamed Gad-Elrab
Mohamed Gad-Elrab

Reputation: 646

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

Upvotes: 0

lkq
lkq

Reputation: 2366

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)

Upvotes: 0

Related Questions