Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 383
Hadas Jacobi Avatar asked Jan 06 '23 08:01

Hadas Jacobi


2 Answers

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;
}
like image 61
Cardano Avatar answered Feb 23 '23 01:02

Cardano


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)};
    }
}
like image 44
ΦXocę 웃 Пepeúpa ツ Avatar answered Feb 23 '23 03:02

ΦXocę 웃 Пepeúpa ツ