简体   繁体   English

使用默认值初始化数组中的对象 - java

[英]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). 我想这意味着我想为数组中的每个索引运行new myObject() (使用默认构造函数)。

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. 我无法在网上找到任何相关内容,我得到的最接近的是在初始化数组后使用Arrays.fill(myArray, new MyObject()) (实际上只是创建一个对象并用指针填充数组) ,或者只是使用循环来遍历数组并初始化每个单元格。

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. 编辑:我意识到这不仅与数组相关,而且与一般声明对象并使它们默认为值/自动初始化有关。

The Java 8 way: Java 8方式:

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. 这将创建一个无限由供应商生成的对象() -> new MyObject()限制了流的总所需的长度,并将其收集到一个数组。

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

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... 并且在for循环中将所有索引设置为初始值...但是如果数组更大,这可能需要一段时间...

Edit: 编辑:

for custom objects is the same just use an anonymous constructor in the init 对于自定义对象,只需在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)};
    }
}

I don't see a way that Java provides to do this. 我没有看到Java提供的方法来做到这一点。

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) 然后将其称为Object[] arr = initialize(YourClass.class, 10)

In Java, the array is initialized with the default value of the type. 在Java中,使用类型的默认值初始化数组。 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. 例如,int default为0.对象数组的单元格的默认值为null因为数组单元格仅包含对包含对象本身的内存槽的引用。 The default reference points to null . 默认引用指向null In order to fill it with another default value, you have to call Arrays.fill() as you mentioned. 为了用另一个默认值填充它,你必须像你提到的那样调用Arrays.fill()。

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

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). 据我所知,没有办法用简单的java做你想要的东西(也就是说可能有一个我不知道的外部库)。

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. 你也可以使用lambda来缩短它,就像卡尔达诺在他的回答中提到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM