How to optimize this method with System.arraycopy?
What's a more efficient way of writing thi开发者_开发技巧s method:
static Foo[][] copy2D(Foo[][] in)
{
Foo[][] ret = new Foo[in.length][in[0].length];
for(int i = 0;i < in.length;i++) {
for(int j = 0;j < in[0].length;j++) {
ret[i][j] = in[i][j].clone();
}
}
return ret;
}
If you did not have the clone() you could replace the inner for with:
System.arraycopy( in[i], 0, ret[i], 0, in[0].length );
But since you're creating a new object in your innermost loop I don't see any other way to do it.
maybe apache commons library which contains the class ArrayUtilsmay help you, but I noticed that you may encounter an IndexOutOfBoundException if this statement is valid:
(in1.length || in[2].length || in[n-1].length) < in[0].length
P.S. I know the statement is not syntactically correct, but it gives you an idea of the problem ;)
精彩评论