Java Reference
In-Depth Information
System.out.println("Using System.arraycopy() method...");
System.out.println("Original Array: " + Arrays.toString(data));
System.out.println("Expanded Array: " + Arrays.toString(eData));
System.out.println("Truncated Array: " + Arrays.toString(tData));
}
// Uses a for-loop to copy an array
public static int[] expandArray(int[] oldArray, int newLength) {
int originalLength = oldArray.length;
int[] newArray = new int[newLength];
int elementsToCopy = 0;
if (originalLength > newLength) {
elementsToCopy = newLength;
}
else {
elementsToCopy = originalLength;
}
for (int i = 0; i < elementsToCopy; i++) {
newArray[i] = oldArray[i];
}
return newArray;
}
}
Using for-loop...
Original Array: [1, 2, 3, 4, 5]
Expanded Array: [1, 2, 3, 4, 5, 0, 0]
Truncated Array: [1, 2, 3]
Using System.arraycopy() method...
Original Array: [1, 2, 3, 4, 5]
Expanded Array: [1, 2, 3, 4, 5, 0, 0, 0, 0]
Truncated Array: [1, 2]
The
Arrays
class is in the
java.util
package. It contains many convenience methods to deal with arrays.
For example, it contains methods for converting an array to a string format, sorting an array, etc. You used the
Arrays.toString() static
method to get the contents of an array in the string format. The method is overloaded;
you can use it to get the content of any type of array in string format. In this example, you used a
for
loop and the
S
ystem.arraycopy()
method to copy arrays. Notice that using the
arraycopy()
method is much more powerful than
that of a
for
loop. For example, the
arraycopy()
method is designed to handle copying of the elements of an array
from one region to another region in the same array. It takes care of any overlap in the source and the destination
regions within the array.
Variable-Length Arrays
You know that Java does not provide variable-length arrays. However, Java libraries provide some classes whose
objects can be used as variable-length arrays. These classes provide methods to obtain an array representation of their
elements.
ArrayList
and
Vector
are two classes in the
java.util
package that can be used whenever variable-length
arrays are needed.