There is no need for an explicit loop here, because you can presumably use System.arraycopy(Object src, int srcPost, Object dest, int destPos, int length)
. First, decide how you want to handle null
input for your array (returning a new one element array is what I would expect). Otherwise, create a new array with room for one more element. Set the first value, then copy everything at an offset of 1. Finally, return the new array. Like,
public static int[] insertValue(int[] src, int value) {
if (src == null) {
return new int[] { value };
}
int[] dest = new int[src.length + 1];
dest[0] = value;
System.arraycopy(src, 0, dest, 1, src.length);
return dest;
}