Java array expansion instance code
- 2020-11-25 07:14:48
- OfStack
In the process of writing a program, we often run out of array space, such as I have initialized an array int []a = {1,2,3,4,5,6,7,8,9,10}; I want to insert one element into the array subscript 3. What do I do? C language is too difficult to implement, you need to call memcpy function 1 to 1, but in java will not be so troublesome, there is a way called array expansion, easy to implement. 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 the 1 A digital ");
// int num = s.nextInt();
// The index of this array can only go to 9
int []a = {1,2,3,4,5,6,7,8,9,10};
// To increase
int []b = Getarray(a,3,100);
Demoe.PrintArray(b);
}
// Case: 1 An array has been initialized, and now its subscript 3 insert 1 An element 100
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 still want to use it a, make a Point to the b
// And then from the end 1 The elements begin and end 1 The first of the elements 1 Copy the elements to the end 1 a
// And so on
for(int i = a.length - 1 ; i > index ; i--){
a[i] = a[i-1];
}
// Don't forget that the elements to be inserted are inserted into the corresponding array coordinates
a[index] = num ;
return a ;
}
}
This can also be done using the library functions in java
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args){
// Scanner s = new Scanner(System.in);
// System.out.println(" Please enter the 1 A digital ");
// int num = s.nextInt();
int []a = {1,2,3,4,5};
int []b = new int[a.length] ;
//1 The source array,
//2 , where to start the source array
//3 , target array
//4 , which location of the target array to start storing
//5 , make a few copies
//System.arraycopy(a, 0, b, 0, a.length);
//Demoe.PrintArray(b);
// capacity ---> A new 1 times
//a = Arrays.copyOf(a, 2*a.length) ;
//Demoe.PrintArray(a);
a = insertArray(a , 3 , 100) ;
// Print the array
System.out.println(Arrays.toString(a));
}
// write 1 Function to any of the array of integers pos Position insert 1 An element value
public static int[] insertArray(int []a , int pos , int value){
if(pos < 0 || pos > a.length + 1) // Returns the source array if the index subscript is incorrect
return a ;
// In the 1 Three elements, first expanded, then copied
a = Arrays.copyOf(a, a.length+1) ;
for(int i = a.length - 1 ; i > pos ; i--){
a[i] = a[i-1] ; // After moving
}
a[pos] = value ;
return a ;
}
}
Operation results:
[1, 2, 3, 100, 4, 5]
conclusion
That's the end of this article on Java array extension example code, I hope to help you. If there is any deficiency, please let me know. Thank you for your support!