gpt4 book ai didi

java - 有没有 "UNIVERSAL"方法来初始化对象数组? ( java )

转载 作者:行者123 更新时间:2023-11-30 03:56:42 24 4
gpt4 key购买 nike

我为每个类使用一个 init 方法。

Spam[] spam1 = new Spam[13];
Spam[] spam2 = new Spam[7];
Spam[] spam3 = new Spam[5];

initSpamArray(spam1);
initSpamArray(spam2);
initSpamArray(spam3);

void initSpamArray (Object[] a) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new Spam();
}
}


Ham[] ham1 = new Ham[13];
Ham[] ham2 = new ham[7];
Ham[] ham3 = new Ham[5];

initHamArray(ham1);
initHamArray(ham2);
initHamArray(ham3);

void initHamArray (Object[] a) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new Ham();
}
}

是否可以定义一种“通用”方法来初始化任何类型的对象?

至少喜欢:

void initObjArray (Object[] a, <s.g. which suitable to transfer Class>) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new <s.g. which suitable to transfer Class>();
}
}

我尝试了很多Google,也尝试使用java反射(Object.getClass(); Constructor.newInstance(); Class.newInstance( ))。然而我并没有成功。

最佳答案

使用 Supplier指定创建实例的方式:

public static <T> T[] fullArray(Class<T> componentType, int n,
Supplier<? extends T> constructor) {
// This introduces no new type-unsafety.
// Array.newInstance has to return Object since it can take a primitive
// component type and !(new int[0] instanceof Object[]), but we know that
// the result is a reference type since type parameters like T can only
// bind to reference types.
@SuppressWarnings("unchecked")
T[] array = (T[]) Array.newInstance(componentType, n);
for (int i = 0; i < n; ++i) {
array[i] = constructor.get();
}
return array;
}

而不是

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

你可以做

Foo[] foos = fullArray(
Foo.class, 42,
new Supplier<Foo>() { public Foo get() { return new Foo(); } });

或者在 Java 8 中

Foo[] foos = fullArray(Foo.class, 42, () -> new Foo());

关于java - 有没有 "UNIVERSAL"方法来初始化对象数组? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22998005/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com