基礎:如何有效的複製和合並陣列

banq發表於2002-12-03
陣列操作快,很多人喜歡用,但陣列是定長的,難以動態擴充套件,一般用合併陣列的辦法。使用clone比較好實現陣列複製:

英文:

It is ok to use clone() for arrays. In the case of arrays that are not of
primitive types, It does a "shallow:" copy meaning it doesn't copy the
objects that are referenced in the array. This is important in the case of
multi-dimensioned arrays. Because they also are just arrays of objects, the
sub-arrays don't get copied.

Use clone() only when you want to create an exact copy of the array, i.e.
same size, same element type.

System.arraycopy works on two existing arrays, so if you use that, you have
to create an empty array first. You would use it if you wanted to copy the
contents of an array to a bigger array (thereby "growing" the array) or if
you want to create an array where the element type is assignment-compatible
with the original array (e.g. going from String[] to Object[]). You can also
use it to move array elements within an array.

相關文章