我有一个类型为 B[]
的数组。我有一个构造函数 A(B b)
。
我想使用它们创建类型为 A[]
的数组。
我可以使用 for 语句来做到这一点,但我想知道是否有更方便(更短)的方法来做到这一点。 (语言语法、静态方法或其他)
public class A {
public A(B b) {
A.a = B.a;
A.b = B.b * B.c;
...
}
}
public class B {
...
}
public class C {
public static B[] getBs() {
B[] bs;
...
return bs;
}
}
void process() {
// From here
B[] bs = C.getBs();
A[] as = new A[bs.length];
for (int i=0; i<bs.length; i++) {
as[i] = new A(bs[i]);
}
// To here
}
最佳答案
就语言的当前1状态而言2,你能做的最好的事情就是这样3 :
interface Transformer<A, B> {
B transform(A a);
}
class ArrayUtils {
@SuppressWarnings("unchecked")
public static <A, B> B[] transformArray(
Class<B> clazz,
A[] a,
Transformer<A, B> transformer
) {
B[] b = (B[])Array.newInstance(clazz, a.length);
for(int i = 0; i < a.length; i++) {
b[i] = transformer.transform(a[i]);
}
return b;
}
}
用法:
Foo[] foos = // some Foo array
Bar[] bars =
ArrayUtils.transformArray(
Bar.class,
foos,
new Transformer<Foo, Bar>() {
public Bar transform(Foo foo) { return new Bar(foo); }
}
);
假设:
class Foo { }
class Bar { public Bar(Foo foo) { } }
1:2014 年(?)将推出一些功能,使它变得更容易。
3:刚刚把这个一起破解了。随时帮助修复任何错误。 :-)
关于java - 使用类构造函数和另一个数组初始化一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18139645/