Reputation: 520
I'm building an application using java.swing. I've got a main panel, a grid panel (which displays squares), and a details panel (which brings up the details on each square and lets you edit them). The squares are also objects.
I have the main panel listening for mouse clicks, and if you click on the grid panel, the grid panel will go through it's ArrayList of squares and find which square you clicked on, returning it. This square is passed by the main panel to the display panel, which then sets it's local variable currentSquare equal to the square being passed in.
Where I'm getting confused is that I can edit currentSquare, and the corresponding square in the ArrayList is being edited! I can change the currentSquare's public variables or use a setter to change them, but the effect is the same regardless. While this is the effect that I'm wanting to have happen, I was under the impression that I would have to have some sort of getters/setters to carry the edited currentSquare back to the ArrayList and replace the old square.
My current theory as to why this is happening is that it has something to do with Java's references, since the square is a custom Object, but I'm not certain that this is the case or what caused this. Ultimately I want to know what I did to cause this situation and if it's good/ok programming practice to leave this as it is or build on this (and if I do build on it working like this, how likely is it that it will break).
Upvotes: 0
Views: 149
Reputation: 63442
In Java, when you call a method with an object, you're not sending a copy of the object, but rather a reference to it. Both the caller and the calleee will refer to the same object and the object will be eligible for garbage collection once all references to it disappear.
Java is called "pass-by-value" because the references themselves are values, just like the primitives are values. When you're calling a method with an object, you're sending the address of the object as a parameter, not a copy of the object. You don't have access to the value of the address, you can only access the object referred to by it. Example:
import java.util.*;
class Test {
private static void test(Map<String, String> a, int b) {
a.put("test", "def");
b = 10;
}
public static void main(String[] args) {
Map<String, String> a = new HashMap<String, String>();
a.put("test", "abc");
int b = 5;
test(a, b);
System.out.println(a);
System.out.println(b);
}
}
{test=def}
5
The above compiles into something like:
test(0x123456, 5);
Upvotes: 5