往数组指定位置添加数值


public class test {


       public static int[] insertArray(int[] arr,int index,int value){
			//新建数组,对原数组扩容
		       int newarr []= new int [arr.length+1];
			//将原数组数据赋值给新数组
			for (int i = 0; i < arr.length; i++) {
		       newarr[i]=arr[i];
		    }
			//将大于i的数据向后移动一位
	        for (int i =newarr.length-1;i>index; i--) {
		       newarr[i]=newarr[i-1];
		     }
			//赋值到index位置
			newarr[index]=value;

			return newarr;
	  }


     public static void main(String[] args) {
       //实现在数组中第五位添加一个数值
       int[] arr =  {34,45,1,34,56,75,23,67,12,4};
        String str=Arrays.toString(insertArray(arr,2,999));
        System.out.println(str);



    //另外,JavaScript splice() 方法
      var fruits = ["Banana", "Orange", "Apple", "Mango"];
      fruits.splice(2,0,"Lemon","Kiwi");

    //输出:Banana,Orange,Lemon,Kiwi,Apple,Mango


    }

}

输出: [34, 45, 999, 1, 34, 56, 75, 23, 67, 12, 4]

你可能感兴趣的:(Java,java基础,数组)