I have a read a lot of posts here regarding inserting a new element in an array but my doubts have not been cleared. I did some more research and came across System.arraycopy()
method to do it. But I somehow feel that it's not efficient. Is there any other way I can do this? Converting the array into an arraylist seems to be confusing as when I tried the Arrays.asList()
, I couldn't add elements to it.
Here is my code that I wrote using System.arraycopy()
:
import java.util.Arrays;
class example{
public static void main(String[] args) {
int[] array = new int[]{2,3,4,5,6,7};
int[] newarray = new int[7];
int indexvalue = 2;
int num = 8;
System.arraycopy(array, 0, newarray, 0, 2);
System.out.println(newarray[2]=8);
System.arraycopy(array, 2, newarray, 3,4);
System.out.println(Arrays.toString(newarray));
}
}
and it gives this output :
run: 8 [2, 3, 8, 4, 5, 6, 7]
BUILD SUCCESSFUL (total time: 0 seconds)
Is there a better way to do this?
EDIT : The reason I am using arrays for this is because the question asks me to insert a new element in an array.