During the process of writing programs, we often encounter situations where there is not enough array space. For example, I have initialized an array int []a = {1,2,3,4,5,6,7,8,9,10}; At this time, I want to insert an element into the position of array subscript 3. What should I do? It is too difficult to implement in C language. You need to call memcpy functions one by one, but it doesn't have to be so troublesome in Java. There is a kind of expansion method called arrays, which can be easily implemented. Let's take a look at the code:
public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System.in); // System.out.println("Please enter a number"); // int num = s.nextInt(); // This array subscript can only reach 9 int []a = {1,2,3,4,5,6,7,8,9,10}; //Extend int first int []b = Getarray(a,3,100); Demoe.PrintArray(b); } //Case: An array has been initialized, and now insert an element 100 into its subscript 3 public static int[] Getarray(int []a , int index , int num){ int src_array_length = a.length ; int []b = new int[src_array_length+1] ; for(int i = 0 ; i < a.length ; i++){ b[i] = a[i] ; } a = b ; //If you want to use a, make a point to b //Next, start from the last element and copy the previous element of the last element to the last one // and so on for(int i = a.length - 1 ; i > index ; i--){ a[i] = a[i-1]; } //Don't forget, insert the element to be inserted into the corresponding array coordinate a[index] = num ; return a ; } }You can also use library functions in java to implement it
import java.util.Arrays; public class HelloWorld { public static void main(String[] args){ // Scanner s = new Scanner(System.in); // System.out.println("Please enter a number"); // int num = s.nextInt(); int []a = {1,2,3,4,5}; int []b = new int[a.length] ; //1, source array //2, where to start the source array //3, target array //4, where to start the target array //5, copy several times //System.arraycopy(a, 0, b, 0, a.length); //Demoe.PrintArray(b); //Scaling--->Scaling doubled//a = Arrays.copyOf(a, 2*a.length) ; //Demoe.PrintArray(a); a = insertArray(a , 3 , 100) ; //Print array System.out.println(Arrays.toString(a)); } //Write a function to insert an element into any pos position of the integer array public static int[] insertArray(int []a , int pos , int value){ if(pos < 0 || pos > a.length + 1) //The index subscript is incorrect, and the source array is returned directly to the return a ; //Put an element, expand the capacity first, and then copy a = Arrays.copyOf(a, a.length+1) ; for(int i = a.length - 1 ; i > pos ; i--){ a[i] = a[i-1] ; //Move back} a[pos] = value ; return a ; } }Running results:
[1, 2, 3, 100, 4, 5]
Summarize
The above is all the content of this article about Java array expansion instance code, I hope it will be helpful to everyone. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!