Reputation:
I have this simple immutable object:
public class Alt {
public LinkedList<Integer> list = new LinkedList<Integer>();
public void refresh() {
Random rand = new Random();
list.clear();
for (int i = 0; i < 50; i++) {
list.add(rand.nextInt(32));
}
}
public void compare(Alt alt) {
for (int i = 0; i < list.size(); i++) {
System.out.println(alt.list.get(i) + " " + list.get(i));
}
}
}
However this class is an immutable object, for example when I run:
Alt a = new Alt();
a.refresh();
Alt b = a;
b.refresh();
a.compare(b);
The values that return are the same, the object b act's like its a shortcut to the object a and is more or less a duplicate. Is there a way to make it so that b is separate? Or am I doing this in completely the wrong way.
Upvotes: 2
Views: 656
Reputation: 1802
There is a misunderstanding in your question. First of all, your class is actually mutable. You can read here about the strategy of defining immutable objects.
Secondly, the observed behavior you mentioned is due to the passing reference. You can read more info here.
Upvotes: 0
Reputation: 12942
Your terminology is wrong. This is not an immutable object. The refresh()
method modifies the object. In the following code will output two different lines:
Alt a = new Alt();
a.refresh();
System.out.println(a.list);
a.refresh();
System.out.println(a.list);
Also, because the field list
is visible from outside the class, it can be modified directly:
Alt a = new Alt();
a.refresh();
System.out.println(a.list);
a.list.set(10, 42);
System.out.println(a.list);
The behaviour you observe is caused by the fact that a = b
does not create a new copy of the object. It only makes the reference b
point to the same object as the reference a
. Since there is only one object, a.compare(b)
will print the same numbers twice.
To make a copy of the object, you will have to program this yourself. In Java, this is often done by a so-called copy constructor:
public Alt(Alt original) {
list = new LinkedList<>(original.list);
}
(Note how that copy constructor calls the copy constructor of LinkedList
, which makes a copy of the list.)
Now you can write:
b = new Alt(a);
and then b
will be a reference to a new object which happens to contain the same data.
Upvotes: 6