Monday, 16 February 2009

Back to Basics: Copying Arrays and other Array Operations

Copying Arrays

One way is to use the clone method which (by default) just does a shallow copy (so it's fine only for primitive one-dimensional arrays).

Another way is to use System.arraycopy(src, 0, dest, 0, length).

Arrays.copyOf(src, nitems) will copy nitems, filling in nulls where appropriate, and copyOfRange(src, a, b) will copy src from a to b. copyOf and copyOfRange are meant to be more efficient than System.arrayCopy.

Array Utils

java.util.Arrays - contains various methods for manipulating arrays (sorting and searching). Arrays has been around since Java2, and is part of the JCF.

Arrays.binarySearch( array, key ). Can be float array, double array, int array.
Arrays.fill(array, value)
Arrays.asList returns the array presented as a java.util.List.

No comments:

Blog Archive