As already mentioned the best Array type to use is a List or ArrayList for inserting elements into that array by way of the ArrayList.add(index, valueToAdd) method. It of course can be done with basic Arrays but a little more work on your part is required to carry out the task as you have already noticed. One possible way might be like this:
public static String[] insertStringArrayElement(String[] original, String value, int atIndex) {
// Make sure the supplied index (k) is within bounds
if (atIndex < 0 || atIndex > original.length) {
throw new IllegalArgumentException("\ninsertArrayElement() Method Error! "
+ "The supplied index value is invalid ("
+ atIndex + ")!\n");
}
String[] tmp = new String[original.length + 1];
int elementCount = 0; //Counter to track original elements.
for(int i = 0; i < tmp.length; i++) {
// Are where we want to insert a new elemental value?
if (i == atIndex) {
tmp[i] = value; // Insert the new value.
i++; //Increment i so to add the orininal element.
// Make sure we don't go out of bounds.
if (i < original.length) {
tmp[i] = original[elementCount]; // Add original element.
}
}
// No we're not...
else {
tmp[i] = original[elementCount]; // Add original element.
}
elementCount++; // Increment counter for original element tracking.
}
return tmp; // Return our new Array.
}
As Andreas has so kindly pointed out, in your original posted code you had declared the list String Array and initialized it to contain 14 elements but in the very next line you reinitialize this array to contain only 4 elements. The first initialization is a waste of oxygen, time, memory, effort, etc since you could have just declared and initialized the Array like this:
String[] list = new String[] {"Bob", "Sal", "Jimmy" ,"John"};
or better yet:
String[] list = {"Bob", "Sal", "Jimmy" ,"John"};
Just something to remember.