Pawel
Pawel

Reputation: 1467

Creating new array

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.

Upvotes: 0

Views: 144

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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.

Upvotes: 1

Related Questions