4

Is there any difference in between these three, assuming a has type ArrayList<T>? (Aside from the fact that the compiler complains about unchecked operations in #3.)

1.

ArrayList<T> a1 = new ArrayList<T> (a);

2.

ArrayList<T> a2 = new ArrayList<T> ();
a2.addAll (a);

3.

ArrayList<T> a3 = (ArrayList<T>) (a.clone());
ajb
  • 30,640
  • 3
  • 52
  • 82

1 Answers1

1

Cloning creates a new instance, holding the same elements. Clone works fine with Collections. So it is better not to use them.

ArrayList<T> a1 = new ArrayList<T> (a);

is a shallow copy and is comparatively faster.

This Thread may help you further

Community
  • 1
  • 1
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319
  • Clone() works fine with Collections although it is considered broken. Correct me if I am wrong. :) – Rahul Tripathi Aug 15 '13 at 17:10
  • The javadoc for [ArrayList.clone](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clone()) says it makes a shallow copy; is the result any different from the constructor, #1? (Not counting performance issues.) – ajb Aug 15 '13 at 17:21
  • Ahh, misunderstood. Then "So it is better not to use them." relates to "creates a new instance". – Joop Eggen Aug 15 '13 at 18:51
  • I fully agree with you!! :) – Rahul Tripathi Aug 15 '13 at 18:51