Cloning something inside a singleton object

bautista :

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?

GhostCat salutes Monica C. :

Here:

protected Object clone() throws CloneNotSupportedException {
  return super.clone();
}

That is basically a "no op". It does not magically copy the content of your list into a new one. And just for the record: for any method, it is really pointless to override, but to then only call the super method implementation. Then you could as well: just not override that method.

So, either use a different mechanism, or really overwrite that method, with custom content to create a new List. Otherwise your clone and the original Item object operate on the same list instance.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117559&siteId=1