简体   繁体   中英

Change original array by another array in java

I created simple insertion method to insert value to array. But i want to need some way to change my original array after using that method. For example my array has 5 numbers. After using that inserting method i need to change it having 6 numbers.

public class inserting {
    public static void main(String[] args) {
        int a[]={5,3,1,6,7};
        insert(0,10,a);
        //i need to change my array like this = [10, 5, 3, 1, 6, 7] after apply insert method
    }
    static void insert(int pos, int val, int arr[]){
        int newArr[]=new int[(arr.length)+1];
        for(int i=arr.length; i>pos; i--){
            newArr[i]=arr[i-1];
        }
        newArr[pos]=val;
        for(int i=0; i<pos; i++){
            newArr[i]=arr[i];
        }
       
        
    }
}

i need to change my a array like this = [10, 5, 3, 1, 6, 7] after apply inserting method

There is nothing wrong with the way you did it. Just return the new array as the return type. But you may want to check out the methods in:

Arrays
System.arraycopy

They have several methods to help copy values.

Here is an example of using the latter.

static int[] insert(int pos, int val, int arr[]){
    int newArr[]=new int[(arr.length)+1];
    System.arraycopy(arr,0,newArr, 0, pos);
    newArr[pos] = val;
    System.arraycopy(arr, pos, newArr,pos+1,arr.length-pos);
    return newArr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM