tags:

views:

79

answers:

3

What's a more efficient way of writing this 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;
}
+2  A: 

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.

Webinator
@OldEnthusiast, good eye, I did not see the `.clone()` part.
Anthony Forloney
A: 

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 ;)

Omar Al Kababji
A: 

This is a bit of C# which could be ported to java quite easily I think.

  IFormatter formatter = new BinaryFormatter();
  Stream stream = new MemoryStream();
  using (stream)
  {
    formatter.Serialize(stream, source);
    stream.Seek(0, SeekOrigin.Begin);
    return (Foo[][])formatter.Deserialize(stream);
  }

Something like this might work but only if it is serializeble. I dunno if it would be more efficient, you'd have to test it.

runrunraygun