Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem dealing with static variables  RSS feed

 
Winston Kok
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm new to Java and I'm trying to create a spanning tree in the desired order with 4 nodes (0,1,2,3). I've got the following code:







What happens is that the input parameter adj and hence the original adjmat inside main gets changed everytime I enter the method "connected", and I don't want this to happen. I understand that this is due to the main method being static and hence adjmat becomes static as well, but how do I change the code such that adjmat only gets modified after coming out of the connected function, and not while inside it?
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Kok wrote:What happens is that the input parameter adj and hence the original adjmat inside main gets changed everytime I enter the method "connected", and I don't want this to happen. I understand that this is due to the main method being static and hence adjmat becomes static as well, but how do I change the code such that adjmat only gets modified after coming out of the connected function, and not while inside it?

This has nothing to do with anything being static.
adj and adjmat are not objects - they are references to objects and they are both referencing the same array, therefore any changes you make to that array in the method using the adj reference will be seen outside the method using the adjmat reference.
The only way to avoid this is to make a copy of the array and pass a reference to that to the method.
 
Winston Kok
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stuart A. Burkett wrote:
Winston Kok wrote:What happens is that the input parameter adj and hence the original adjmat inside main gets changed everytime I enter the method "connected", and I don't want this to happen. I understand that this is due to the main method being static and hence adjmat becomes static as well, but how do I change the code such that adjmat only gets modified after coming out of the connected function, and not while inside it?

This has nothing to do with anything being static.
adj and adjmat are not objects - they are references to objects and they are both referencing the same array, therefore any changes you make to that array in the method using the adj reference will be seen outside the method using the adjmat reference.
The only way to avoid this is to make a copy of the array and pass a reference to that to the method.


Thank you for the quick reply. Just verified this and it works, thanks so much!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!