• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to pass an array, not a reference, to a method  RSS feed

 
Jim Venolia
Ranch Hand
Posts: 312
2
Chrome Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to pass an array to a method. Problem is, I don't want to pass a reference to the array. If the method modifies the array I don't want the original array to change.

Right now I'm looking at copying the array and passing the copy, but that seems like an extra step. That said, I don't think it's possible to do what I want, but I thought I'd ask.

 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to pass an array without the method being able to modify it then you are going to need to create a copy of the array.

Do you come from a C++ background? If so, Java doesn't allow variables to hold object values like C++ does. Even though all method calls use pass-by-value semantics in Java, the value that is passed will be the value of the reference to the Object.

Does your code strictly require arrays though? If you use a list instead it is possible to create unmodifiable Lists.
 
Piet Souris
Master Rancher
Posts: 2043
75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, keep in mind that the elements of the array should be immutable,
otherwise a copy of the array won't help.

Greetz,
Piet
 
Jim Venolia
Ranch Hand
Posts: 312
2
Chrome Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After a couple games of Call of Duty I realized a better way to solve my problem. Correct diagnosis, wrong solution.

Thanks for the replies.

edit: No harm in saying I decided to write a brute force Sudoku solver this morning. The problem I had was my recursive calls were modifying the 9x9 array, then not putting it back when it didn't find a solution. My initial solution was "well dang, pass a new array to the recursive call". After playing CoD I realized "well dang, don't change the array. Modify the verify routine to accept an "Is this value OK" argument without modifying the array.

In my defense, I've spent 35+ years on embedded systems, where recursion is Not A Good Thing (tm) as it tends to blow your small stack out of the water pretty quickly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!