Java数组对象初始化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21820176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java array object initialization
提问by user2899587
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.
感谢您的回复。
采纳答案by Weibo Li
Impossible as far as I know.
The code 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 = new Tile[20];
只是创建了一个引用数组。要填充数组,您应该创建一个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));
回答by Radiodef
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. 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):
在没有 Java 8 的情况下,还有几种方法可以通过使用反射来做到这一点。如果类有一个复制构造函数(一个以它自己的类的对象作为参数的构造函数),你可以这样做:
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. The lambda is great.
反射比 lambda 更不稳定,尤其是在处理子类型和原语时。拉姆达很棒。
回答by Adrian Shum
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:
您必须先创建数组实例,然后填充数组中的单个元素:
e.g.
例如
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));