I am trying to copy the elements from src (Array 1) to tgt (Array 2) using recursion. Len is an integer value that determines how many of the elements should be transferred. For example, if len is 4, I take 4 elements out of Array 1 and transfer them to Array 2.
Start is the starting location of array src, and this value is transferred to location start2 of array tgt. Then I recursively copy the remaining len-1 elements. Returning out of bound exception.
public void arraycopy(double[] src, int start, double[] tgt, int start2, int len){
if(len < 1) return;
if(len > src.length) return;
tgt[start2] = src[start];
arraycopy(src, start + 1, tgt, start2 + 1, len);
}
First, you are not treating
len
as the number of characters to copy. You are treating it as an ending index with this condition:You can change it to
but at that point,
len
is already greater than0
because the base caselen < 1
is already past. You can remove thatif
condition entirely.Second, pass
len - 1
in the recursive call:Third, if
len
is greater than the source array'slength
:then all you do is
return
, leading to an uncopied array and a confused caller. I would remove this line entirely. You can let Java throw theArrayIndexOutOfBoundsException
, passing it to the caller. If you must perform the bounds check, then test it yourself properly, for both the source and destination arrays.