Java Reference
In-Depth Information
0 i numberOfRuns runningTimes.length
xxxxx y zzzzzzzz
0 i numberOfRuns runningTimes.length
xxxxx zzzzzzzz
How this is done depends on whether the order of the values in the table
must remain the same. If so, then code of the following form is needed:
numberOfRuns= numberOfRuns - 1;
Copy runningTimes[i + 1..numberOfRuns]
to runningTimes[i..numberOfRuns- 1 ]
Obviously, the time taken is proportional to the number of values to be copied.
If the order of the values does not matter, there is a much simpler and faster
way to perform the task: just move the last element to runningTimes[i] :
numberOfRuns= numberOfRuns - 1;
runningTimes[i]= runningTimes[numberOfRuns];
(This works even if i = numberOfRuns - 1 , in which case the last element is
being removed. In this case, the second assignment has no effect, since it assigns
runningTimes[i] to runningTimes[i] . It is better to leave the code like this
than to use an if -statement to test for a special case; avoid unnecessary case
Changing the size of an array
As mentioned earlier, the size of an array object is determined when the array is
first created, and it cannot be changed. However, it is possible to make it look
like the array size has been changed by creating a second, larger, array and copy-
ing the first array into the beginning of the second. Naturally, doing this takes
time, and this copying should not be done often. To prevent frequent copying,
and also limit unused space, it is common to double the size of the array. Here is
code to perform this service:
// Double the size of array runnningTimes (if size > 0 )
double [] temp= new double [2 * runningTimes.length];
System.arraycopy(runningTimes , 0 , temp ,
0 , runningTimes.length);
runningTimes= temp;
This code can be executed whenever array runningTimes runs out of space,
instead of simply giving an error message and aborting program execution. See
also ProgramLive activities 8-4.4 and 8-4.5.
Search WWH ::

Custom Search