简体   繁体   English

Java数组对象初始化

[英]Java array object initialization

I just want ask, is it possible to initiliaze more objects with same constructor in one command? 我只想问,是否可以在一个命令中使用相同的构造函数初始化更多对象?

Example of code: 代码示例:

Tile[] tiles = new Tile(5,5)[20];

Thanks for response. 谢谢你的回复。

Impossible as far as I know. 据我所知,不可能。 The code Tile[] tiles = new Tile[20]; 代码Tile[] tiles = new Tile[20]; just creates an array of references. 只是创建一个引用数组。 To fill the array, you should create a Tile object and then assign the reference to one index of the array, such as: 要填充数组,您应该创建一个Tile对象,然后将引用分配给该数组的一个索引,例如:

tiles[0] = new Tile(5,5);

If all elements of the array pointing to the same object is OK, you can full fill the array simply use: 如果指向同一对象的数组的所有元素都正常,则可以完全填充数组,只需使用:

Tile tiles = new Tile[20];
Arrays.fill(tiles, new Tile(5,5));

No, you have to use a loop. 不,你必须使用一个循环。

Tile[] tiles = new Tile[20];
for(int i = 0; i < tiles.length; i++) {
    tiles[i] = new Tile(5, 5);
}

However, it is nice that in Java 8 we will be able to shorten this using the new Supplier class and a helper method. 但是,在Java 8中,我们可以使用新的Supplier类和辅助方法来缩短它。

static <E> E[] fill(E[] arr, Supplier<? extends E> supp) {
    for(int i = 0; i < arr.length; i++) {
        arr[i] = supp.get();
    }

    return arr;
}

We can then do the following: 然后我们可以执行以下操作:

Tile[] tiles = fill(new Tile[20], () -> new Tile(5, 5));

I think that's sort of nifty. 我认为这有点漂亮。

There's also a couple ways to do this without Java 8 by using reflection. 通过使用反射,没有Java 8,还有几种方法可以做到这一点。 Here's a way you can do it if the class has a copy constructor (a constructor that takes an object of its own class as an argument): 如果类具有复制构造函数(将其自己的类的对象作为参数的构造函数),则可以使用以下方法:

static <E> E[] duplicate(E[] arr, E element) {
    @SuppressWarnings("unchecked")
    Class<? extends E> cls = (Class<? extends E>)element.getClass();

    try {
        Constructor<? extends E> ctor = cls.getConstructor(cls);
        for(int i = 0; i < arr.length; i++) {
            arr[i] = ctor.newInstance(element);
        }
    } catch(Exception e) {
        e.printStackTrace(System.err);
    }

    return arr;
}

So for example: 例如:

String[] arr = fill(new String[5], "Hello world!");

Reflection is a bit more unstable than the lambda, especially when dealing with subtypes and primitives. 反射比lambda更不稳定,特别是在处理子类型和基元时。 The lambda is great. lambda很棒。

First, it is even not possible to initialize an object array with non-null value in one line (ok, except using {...} or filling them with same reference but I think it is not what you want) 首先,甚至不可能在一行中初始化具有非空值的对象数组(好吧,除了使用{...}或用相同的引用填充它们但是我认为它不是你想要的)

You gotta create instance of array first, and fill individual element in the array: 你必须首先创建数组的实例,并填充数组中的单个元素:

eg 例如

Foo[] myArray =new Foo[10];
for (int i = 0; i < myArray.length; ++i) {
    myArray = new Foo();
}

If you are just looking for shorter code that you don't want to write the loop again and again, here is one option for you: 如果您只是在寻找不想一次又一次地编写循环的更短代码,这里有一个选项:

write a little util like this: 写一个像这样的小工具:

public class ArrayUtil {
  public static T[] fillArray(T[] array, ArrayElementFactory elementFactory) {
    for (int i = 0; i< array.length; ++i) {
      array[i] = elementFactory.create(i);
    }
    return array;
  }
}
public interface ArrayElementFactory<T> {
  T create(int i);
}

The way to use is something like 使用的方式是这样的

Foo[] fooArray = fillArray(new Foo[10], new ArrayElementFactory<Foo>() {
                                        Foo create(int i) { return new Foo(10,10); }};

If you are using Java8, I believe (haven't tried) you can use lambda expression which give you something like 如果您使用的是Java8,我相信(没有尝试过)您可以使用lambda表达式来为您提供类似的东西

Foo[] fooArray = fillArray(new Foo[10], i -> new Foo(10,10));

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

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