This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
So my question is: Does System.arraycopy() accept all sorts of arrays? Specifically, I'm interested in copying non-primitive arrays. But I've come to conflicting conclusions through my own tests. When copying arrays of String objects, arraycopy() seems to work fine. My 2nd array (the copy) seems to be an entirely separate entity from my original array. So if I alter the 2nd array, the first/original remains unchanged. -- However -- When copying my own objects, it seems regardless of what sort of member variables are in my object I don't get a valid copy. I seem to only gain reference to the original object. So any change I make to my supposed copy changes the value in the first/orginial. Is this reasonable behaviour? Is my testing flawed? Thanks! Spencer
Strings are immutable. So in your first test, there's no way to tell if it's a deep or shallow copy just by seeing if you can change them. Does this give you the clues you need? bear [ March 25, 2003: Message edited by: Bear Bibeault ]
You are getting a copy of the array. The array just hold references to objects, it does not hold the objects themselves. The copy holds an identical reference to the same object. You can change the second array to reference a DIFFERENCT object after the copy. But if you act on an element in the array it will modify then same object that the original array would have modified. This is very similar to the topic of Deep and shallow cloning. A deep clone also creates copies of the objects that are referenced. Most cloning operations are shallow clones and you get the same results as with arraycopy().
"JavaRanch, where the deer and the Certified play" - David O'Meara