0

I have an object anObject with two private member variables:

public class anObject {
    private String name;
    private ArrayList<String> myList = new ArrayList<String>();
}

I have a constructor:

public anObject() {
    name = "";
}

I have my copy constructors:

public anObject(anObject copy) {
this();
newObject(copy);
}

public void newObject(anObject copyTwo) {
    name = copyTwo.name;
    // How to deep copy an ArrayList?
}

But how can I "deep copy" all the elements of my ArrayList in copyTwo, to my this.myList?

I have looked at the other questions on SO but their ArrayLists all contain objects whereas mine just contains Strings. Thanks for any help!

3
  • 1
    What makes you think a String is not an object? Commented May 5, 2017 at 18:50
  • If you want a deep copy for your list, you just need a foreach in your list Commented May 5, 2017 at 18:50
  • ArrayList has a copy constructor, you can use that. Commented May 5, 2017 at 18:51

2 Answers 2

4

create a new reference to list, since your list is holding strings and strings are immutable you can do:

List<String> copyString = new ArrayList<>(original);
Sign up to request clarification or add additional context in comments.

6 Comments

So this won't be a problem with what I have been seeing as a "Shallow Copy"? I don't want changes to one object to affect the other.
You are using a List of String. It cannot .
@davidxxx great Thanks!
Java strings are immutable, so that won't be a problem. If the list would contain mutable reference types, you would need to deep copy the elements as well.
@MickMnemonic Gotcha. And do I have to create a List or can I still use an ArrayList?
|
1

You can deep copy using a new collection. Changes in new collection won't affect the previous list

List<String> copyTwo= new ARrayList<String>();
copyTwo.addAll(myList );

4 Comments

Why not: List<String> copyTwo= new ArrayList<String>(myList);?
Hi, here on stackoverflow, we don't just provide the questioneer with code. We provide them with an explanation of why this will solve their problem, or how it works. Please edit your answer to reflect this mentality :)
another option to do that
@assylias Do I have to use List or can I still use ArrayList?

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.