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.

Community
  • 1
  • 1
Pawel
  • 1,457
  • 1
  • 11
  • 22

1 Answers1

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386