Maybe I'm just having a blackout but I cant find a feasible way to resolve my problem.
I have a singleton object of Class A
containing an ArrayList<Item>
. In Class C
I need a specific Item
of ArrayList<Item>
(clone it). While ArrayList<Item>
should be unchanged, I need to apply some modifications to the Item
in Class C
. I tried implementing Cloneable in Class Item
like this:
public class Item implements Cloneable {
private ArrayList<String> mSize = new ArrayList<>();
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void modifySomething() {
mSize.clear();
}
}
Afterwards I wanted to get the Item
like this:
class C {
void foo() {
Item item = null;
try {
item = (Item) A.getInstance().getItems().get(0).clone();
item.modifySomething();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
The problem is that the Item item
also gets modified in the singleton object.
Q: Did i take the wrong approach to this? How can I get the desired behaviour?