0

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);
}
4
  • It looks like what you're doing is just fine. Be careful though; if any of the fields are references, they're going to be copied over and it sounds like that isn't what you want. Commented May 18, 2016 at 15:31
  • 1
    List<MyObject> firstList = getArrayListFromSQLiteDb(criteria); and List<MyObject> secondList = new ArrayList<MyObject>(firstList); Commented May 18, 2016 at 15:32
  • @ManuAG If onky they would read the documentation... Commented May 18, 2016 at 15:33
  • @Manu & DjMethaneMan: And if you would read the question, you would understand that the asker doesn't just want a copy of the list, he wants a deep copy that also copies all contained objects (So that both lists have different objects in them). Neither the copy constructor nor the clone() function of ArrayList do that. Commented May 18, 2016 at 15:37

1 Answer 1

3

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should probably also mention that this will only work if the lists contents are cloneable and implement the clone() method correctly. Otherwise you will get a CloneNotSupportedException

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.