0

The question is very simple. Is any simple and fast way to create new (new references) array or it has to be done manually?

Example:

Collection<A> c = new ArrayList<A>();
c.add(new A());
c.add(new A());
c.add(new A());

A[] a1 = c.toArray(new A[0]);
System.out.println("a1: " + Arrays.toString(a1));
System.out.println("c: " + c);

A[] a2 = Arrays.copyOf(a1, a1.length);
System.out.println("a2: " + Arrays.toString(a2));

All created arrays has the same references. I want array with new elements with the same content as old elements. Copies of old elements.

Answer is: How do you make a deep copy of an object in Java? . Now I see that this question is duplicate.

6
  • 8
    Not sure if I understand the question: do you mean you want a deep copy instead of a shallow copy? Commented Sep 2, 2013 at 16:20
  • Is this a shallow clone (in which just the collection is new) or a deep clone (in which the actual objects in the collection are copied Commented Sep 2, 2013 at 16:21
  • 2
    If u r looking for deep copy try serialization Commented Sep 2, 2013 at 16:21
  • 3
    Deep copies are expensive. Generally I write code so I never need to do that. Commented Sep 2, 2013 at 16:24
  • 1
    Please check if this helps you out: javatechniques.com/blog/faster-deep-copies-of-java-objects got from: stackoverflow.com/questions/64036/… Commented Sep 2, 2013 at 16:26

1 Answer 1

1

If you want to create a deep copy of the array (meaning: with freshly created references to each of its elements), there are several alternatives, including:

  • Serialize/deserialize the array (see Apache's SerializationUtils)
  • Manually copying each element (and that element's attributes, recursively)
  • Using reflection explicitly
  • Using a copy constructor

... And so on. Look in stack overflow, there are several posts discussing the subject.

Sign up to request clarification or add additional context in comments.

Comments

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.