• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array.clone() not producing a distinct copy?  RSS feed

 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to create two arrays, initialize one of them, then set the second one equal to the values of the first without making it simply a reference to the first array. At first i tried setting the arrays equal to each other, but that only produced a reference array. Next I tried using array.clone() (shown below), but that didn't work either. I understand why the first method didn't work, but not why the second way didn't. Anyone know why, or a better way to do what I'm trying to do?



 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Clone() is copying "the array". The problem is that "the array" is the top level array and not the nested array.

You can avoid this problem by looping through the arrays and cloning each one. This is called a "deep copy" if you want to read more about it.
 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alright, so now I've modified my main class code to be as follows:



And I'm trying to write a method called copyOf that will produce a deep copy of my 2 dimensional array using array.clone.
However, I'm having trouble on this front. This is what I have so far:



Unfortunately, I have no idea why the errors are occuring. I tried looking up the int cannot be dereferenced error,
but I don't even what it means, much less why its occuring in this instance. Any ideas?
 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, here's a more readable version of the second class with the copyOf method

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!