Initializing an object in an array with a default value - java
Asked Answered
L

6

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.

Lolita answered 30/3, 2016 at 14:50 Comment(6)
This behavior is well define in the JLS.Paleo
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)Aegospotami
could you elaborate on what this does exactly? thanks!Lolita
@Aegospotami You should make this an answer.Conditioner
@Aegospotami That's brilliant using a Java 8's feature.Drillstock
@HadasJacobi elaborated below!Aegospotami
A
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;
}
Aegospotami answered 30/3, 2016 at 15:9 Comment(0)
V
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)};
    }
}
Volteface answered 30/3, 2016 at 14:53 Comment(4)
I don't think it's what he wants. He's talking about objects.Drillstock
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 :))Lolita
Ohhh, I get it now, please take a look at the update in the answer with the SOFPointClassEminent
@HadasJacobi Sorry about the 'He'. :)Drillstock
B
1

You can use Arrays.setAll since Java 8:

var arr = new MyObject[5];
Arrays.setAll(arr, i -> new MyObject());
Braziel answered 16/12, 2023 at 0:52 Comment(0)
D
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)

Drillstock answered 30/3, 2016 at 15:5 Comment(0)
F
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());
Fullblown answered 30/3, 2016 at 15:6 Comment(2)
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...)Lolita
Ok, I got what you need .. so either a loop or in Java 8 use stream way explained aboveFullblown
N
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.

N answered 30/3, 2016 at 15:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.