• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to set one array equal to another without making it a reference to the other?  RSS feed

 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm trying to find a way to create one array, and then set it equal to the values in another array without making it a reference to the other array. Here was my initial attempt to set one array to the other, and then to modify one part of the new array. The problem I am encountering is that the line "test2=test1" seems to not only set test2 equal to the values of test1, but it also means that when I modify test2, test1 is modified as well. Is there any way set test2's values equal to test1's values without making test2 essentially a reference to test1?

 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to copy the array if you want them to be distinct.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use one of the copyOf(...) methods in class java.util.Arrays to create a copy of an array.
 
Louis Lewis
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, that worked.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Louis Lewis wrote:Thanks, that worked.

These days, you can also use:
test2 = test1.clone();

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