0

For example let's say i have a Class MyObject

class MyObject{
int i;
String s;

My(int i,String s){
    this.i = i;
    this.s = s;
}
...
setters/getters/toString
}

and that i have a list with objects of that Class(i dont know if that make a different what kind of list it is but i want this to work with ObservableList)

ObservableList<MyObject> listOne = FXCollections.observableArrayList();
MyObject one = new MyObject(1,"foo");
MyObject two = new MyObject(2,"boo");

Now i want to make new ObservableList from objects of listOne but i want that new list have objects with different reference

if i make it like this

ObservableList<MyObject>listTwo=FXCollections.observableArrayList(listOne);

when i do something like this

listOne.get(0).setI(500);

It will also effect object in listTwo

What is best practice to avoid this ? How can i make new list of some list with objects of that list which are treat as different objects ?

I could do something like this

for (MyObject object : listOne) {
        MyObject cloneObject = new MyObject(object.getI(),object.getS());
        listTwo.add(cloneObject);
}

I just hope that there is a better way

Makoto
  • 104,088
  • 27
  • 192
  • 230
Adrian
  • 149
  • 3
  • 16
  • This is typically referred to as a "deep copy" btw. – Carcigenicate Aug 03 '18 at 14:43
  • The better way would probably be to use immutable objects, to be able to share the same objects without any problem. But with mutable objects, then what you have is basically the only way. Of course you could make a copy constructor, but the principle is the same. – JB Nizet Aug 03 '18 at 14:44

0 Answers0