1.9. Cloning and Reversing Arrays
Problem
You need to reverse and clone the contents of an array.
Solution
Use ArrayUtils.clone()
and ArrayUtils.reverse()
methods from Commons Lang. Example 1-5 demonstrates the reversal and cloning of a
primitive array full of long primitives.
Example 1-5. Cloning and reversing a primitive array with ArrayUtils
import org.apache.commons.lang.ArrayUtils;
long[] array = { 1, 3, 2, 3, 5, 6 };
long[] reversed = ArrayUtils.clone( array );
ArrayUtils.reverse( reversed );
System.out.println( "Original: " + ArrayUtils.toString( array ) );
System.out.println( "Reversed: " + ArrayUtils.toString( reversed ) );The array is cloned and reversed, and the contents
of the original and the reversed array are displayed as output using
ArrayUtils.toString( ):
Original: { 1, 3, 2, 3, 5, 6 }
Reversed: { 6, 5, 3, 2, 3, 1 }Discussion
In Example 1-5, clone( ) returns
a reference to a new array, and reverse( )
operates on the array reference supplied as a parameter. It is
important to realize that while clone( ) leaves
the original array alone, reverse( ) operates
directly on the supplied array. In addition to supporting all
primitive arrays, ArrayUtils.clone( ) and
ArrayUtils.reverse( ) work with object arrays. If
array had been an array of Long
objects, the code would bear a striking resemblance to the previous
example.
The only difference between Examples Example 1-6 and
Example 1-5 is the type of array being cloned and
reversed. Again, ArrayUtils.toString( ) is used to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access