Consider the following:
public class Foo {
private String name;
public Foo(String name) {
this.name = name;
}
public String get() {
return name;
}
public void set(String name) {
this.name = name;
}
}
import java.util.ArrayList;
A container class:
public class FooContainer {
private ArrayList<Foo> foos;
public FooContainer(int nbrOfFoos) {
foos = new ArrayList<Foo>(nbrOfFoos);
}
public void add(Foo foo) {
foos.add(foo);
}
public void printFoos() {
for(Foo foo: foos) {
System.out.println(foo.get());
}
}
}
A simple test:
public class FooTest {
public static void main(String[] args) {
Foo foo = new Foo("Long");
FooContainer cont = new FooContainer(1);
cont.add(foo);
cont.printFoos();
foo.set("John");
cont.printFoos();
}
}
Of course, when executed, the test program prints "Long" and then "John".
Is it poor design to have a program where this is not desirable, i.e. where one would not like the name of the Foo to change?
Is the only workaround to copy/clone the object when passed to the add method?