logo

Common Operations on Arrays

Copying Arrays

Let src be an array of Stuff. You want to copy it to the array dest. How would you do it?

Using a for Loop

The most obvious solution to this problem involves iterating over the array with a for loop. Simple, but not very elegant.

Stuff[] dest = new Stuff[src.length];

for (int i = 0; i < src.length; i++)
{
    dest[i] = src[i];
}

After writing that same loop more than a couple of times, one gets the feeling there should be a better way... There is!

Using clone()

If you need to make a copy of the entire array, then it's really a cloning operation, and you should do just that: clone() works on arrays just fine.

Stuff[] dest = null;
dest = (Stuff[]) src.clone();

Depending on your compiler, you may have to catch a CloneNotSupportedException. When dealing with arrays this error is completely spurious, and you can safely ignore it.

Using System.arraycopy()

Quite often you may want to copy only a slice of the entire array. You can do so by using the very efficient System.arraycopy(). Of course it can also be used to copy the entire array, as the example below illustrates.

Stuff[] dest = new Stuff[src.length];

System.arraycopy( src,         // source array
                  0,           // source index
                  dest,        // destination array
                  0,           // destination index
                  src.length   // copy length 
                );

Because System.arraycopy() is guaranteed to work even with the two arrays overlap, it can be used as a shift operator for arrays! This lets you move slices around, inside of a given array.

For example, consider the following array:

char[] a = { 'a', 'b', 'c', 'd', 'e', 'f' };

To move a slice three elements long, starting at index 1, to index 2, we would do:

System.arraycopy( a, 1,  a, 2,  3 );

See figure 1.

Figure 1. Array shift with System.arraycopy().
Figure 1. Array shift with System.arraycopy().

System.arraycopy() has been available since JDK 1.1. Oh, and did I mention it is faster than any loop you could ever write? Use it to your advantage!

Filling, Sorting, Searching, and Comparing Arrays

JDK 1.2 introduced the java.util.Arrays class, a mixed bag of utilities for manipulating arrays. All methods are overloaded to support any primitive type as well as objects. They are fast and type-safe.

equals(a[], b[])
Returns whether the two arrays are equal.
fill(target[], value)
fill(target[], from, to, value)
Fills the array (or the array slice) with the specified value.
sort(target[])
sort(target[], from, to)
Sorts the entire array, or only the slice between the from and to indices. The array is sorted in place.
binarySearch(target[], key)
Returns the index of the key in the target array. The array must have been sorted prior to calling this method. A negative value is returned if the key could not be found. Since this is a binary search, on average it will take log2(target.length) tests to find the key.

Conclusion

Most array manipulations don't require you to a hand-code a specialized routine. By knowing what facilites are available through the JDK libraries, your code will be simpler, faster, and more robust.


Copyright © 2000-2007 Renaud Waldura <renaud@waldura.com>