Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When does System.arraycopy() work?

 
Spencer J Lee
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64188
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic