Java Reference
In-Depth Information
Limitations of Using Arrays
An array in Java cannot be expanded or shrunk after it is created. Suppose you have an array of 100 elements, and
later, you need to keep only 15 elements. You cannot get rid of the remaining 85 elements. If you need 135 elements,
you cannot append 35 more elements to it. You can deal with the first limitation (memory cannot be freed for unused
array elements) if you have enough memory available to your application. However, there is no way out if you need to
add more elements to an existing array. The only solution is to create another array of the desired length, and copy the
array elements from the original array to the new array. You can copy array elements from one array to another in
two ways:
Using a loop
static arraycopy() method of the java.lang.System class
Suppose you have an int array of the length originalLength and you want to modify its length to newLength . You
can apply the first method of copying arrays as shown in the following snippet of code:
Using the
int originalLength = 100;
int newLength = 15;
int[] ids = new int[originalLength];
// Do some processing here...
// Create a temporary array of new length
int[] tempIds = new int[newLength];
// While copying array elements we have to check if the new length
// is less than or greater than original length
int elementsToCopy = 0;
if (originalLength > newLength) {
elementsToCopy = newLength;
}
else {
elementsToCopy = originalLength;
}
// Copy the elements from the original array to the new array
for (int i = 0; i < elementsToCopy; i++){
tempIds[i] = ids[i];
}
// Finally assign the reference of new array to ids
ids = tempIds;
Another way to copy elements of an array to another array is by using the arraycopy() method of the System class.
The signature of the arraycopy() method is as follows:
public static void arraycopy(Object sourceArray, int sourceStartPosition,
Object destinationArray,
int destinationStartPosition,
int lengthToBeCopied)
 
Search WWH ::




Custom Search