AJJ
AJJ

Reputation: 2074

Making a new ArrayList containing objects the same as the first list?

I have an ArrayList containing custom objects.

What is the best way to make a separate ArrayList that has the exact same content, but isn't using the same references? As in, if I edit the first object in list1, it doesn't touch the first object in list2, but otherwise they look the same through and through.

Is it considered correct / good practice to do the following, or is there a built-in way?

List<MyObject> firstList = getArrayListFromSQLiteDb(criteria);
List<MyObject> secondList = new ArrayList<>();

for (MyObject object : firstList) {
    MyObject newObject = new MyObject();
    newObject.setField1(object.getField1());
    newObject.setField2(object.getField2());
    newObject.setField3(object.getField3());
    secondList.add(newObject);
}

Upvotes: 0

Views: 80

Answers (1)

Daniel Almeida
Daniel Almeida

Reputation: 362

A simple way of doing this would be to clone the original ArrayList, thus not sharing references and having the other list remain untouched when you alter the original one. As @911DidBush mentioned, this will only work if the lists contents are cloneable and implement the clone() method correctly.

List<MyObject> firstList = getArrayListFromSQLiteDb(criteria);
List<MyObject> secondList = new ArrayList<>();

for(MyObject obj : firstList) {
    secondList.add(obj.clone());
}

Upvotes: 3

Related Questions