aspose file tools*
The moose likes Java in General and the fly likes When does System.arraycopy() work? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When does System.arraycopy() work?" Watch "When does System.arraycopy() work?" New topic
Author

When does System.arraycopy() work?

Spencer J Lee
Ranch Hand

Joined: Mar 19, 2003
Posts: 30
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
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61756
    
  67

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 ]

[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When does System.arraycopy() work?