Created
July 9, 2013 23:21
-
-
Save ryanlecompte/5962188 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cheap way to deep clone an arbitrarily-deep nested array | |
def deepCopy[T](array: Array[T]): Array[T] = { | |
import java.io._ | |
val bos = new ByteArrayOutputStream() | |
val oos = new ObjectOutputStream(bos) | |
oos.writeObject(array) | |
val bis = new ByteArrayInputStream(bos.toByteArray) | |
val ois = new ObjectInputStream(bis) | |
ois.readObject().asInstanceOf[Array[T]] | |
} | |
scala> val a = Array(Array(1,2,3), Array(4,5,6), Array(7,8,9)) | |
a: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)) | |
scala> val c = deepCopy(a) | |
c: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)) | |
scala> a(0)(0) = 9999 | |
scala> a | |
res3: Array[Array[Int]] = Array(Array(9999, 2, 3), Array(4, 5, 6), Array(7, 8, 9)) | |
scala> c | |
res4: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment