[jgap-users] Follow-up re: Cloning
Brought to you by:
klausikm
From: Johnathan K. <jk...@rs...> - 2004-01-09 16:51:07
|
After a little bit more digging I discovered a name for what I'm looking to do: A deep copy of the Chromosome. The typical clone method only returns a shallow copy of the object. Apparently there are ways to implement a deep copy on a complex object, but the methods are frequently slow. A quick search turned up a couple of interesting web pages: http://javatechniques.com/public/java/docs/basics/faster-deep-copy.html and also the following (taken from http://forum.java.sun.com/thread.jsp?thread=474281 <http://forum.java.sun.com/thread.jsp?thread=474281&forum=54&message=2197444 > &forum=54&message=2197444): Thanks for the suggestion to use object serialization. However, this technique will undoubtedly prove far too slow for my needs. I've come up with a way to deep copy using cloning. I'm sure it's substantially faster than serialiazation although the code seems somewhat unwieldy. Does anyone have a cleaner yet reasonably fast way of doing this? public Object clone() { try { ClassA copy = (ClassA)super.clone(); copy.array = (ClassB[][])array.clone(); for (int i = 0; i < copy.array.length; i++) { copy.array[i] = (ClassB[])copy.array[i].clone(); for (int j = 0; j < copy.array[i].length; j++) { copy.array[i][j] = (ClassB)copy.array[i][j].clone(); } } return copy; } catch (CloneNotSupportedException e) { return new InternalError(e.toString()); } } Thanks, John C. I guess I was hoping that there was an existing deep-copy method for the Chromosome, but I'm now guessing probably not. Cheers, JK |