Java中数组是不可变的,但是可以通过本地的arraycop来进行数组的插入,删除,扩张。实际上数组是没变的,只是把原来的数组拷贝到了另一个数组,看起来像是改变了。
语法:
System.arraycopy(a,index1,b,index2,c)
含义:从a数组的索引index1开始拷贝c个元素,拷贝到数组b中索引index2开始的c个位置上。
1 package cn.hst.hh; 2 3 import java.util.Scanner; 4 5 /** 6 * 7 * @author Trista 8 * 9 */ 10 public class TestArrayCopy { 11 public static void main(String[] agrs) { 12 Scanner a = new Scanner(System.in); 13 System.out.println("请输入数组(注意空格):"); 14 String s = a.nextLine(); 15 String[] s1 = s.split(" "); //拆分字符串成字符串数组 16 System.out.println("请输入你要插入的元素的个数:"); 17 int n = a.nextInt(); 18 System.out.println("请输入你要插入的位置:"); 19 int index = a.nextInt(); 20 s1 = addArray(s1,n,index); 21 print1(s1); 22 23 // System.out.println("请输入需要扩大元素的个数:"); 24 // int n = a.nextInt(); 25 // s1 = extendArray(s1,n); 26 // print1(s1); 27 // 28 // System.out.println("请输入你要删除元素的位置:"); 29 // int n = a.nextInt(); 30 // s1 = delArray(s1,n); 31 // print1(s1); 32 } 33 34 35 //扩张数组,n为扩大多少个 36 public static String[] extendArray(String[] a,int n) { 37 String[] s2 = new String[a.length+n]; 38 System.arraycopy(a,0, s2, 0, a.length); 39 return s2; 40 } 41 //删除数组中指定索引位置的元素,并将原数组返回 42 public static String[] delArray(String[] b,int index) { 43 System.arraycopy(b, index+1, b, index, b.length-1-index); 44 b[b.length-1] = null; 45 return b; 46 } 47 48 //插入元素 49 public static String[] addArray(String[] c,int n,int index) { 50 String[] c1 = new String[c.length+n]; 51 String[] a1 = new String[n]; 52 if(index==0) { 53 System.arraycopy(c, 0, c1, n, c.length); 54 }else if(index==c.length) { 55 System.arraycopy(c,0,c1,0,c.length); 56 57 }else { 58 System.arraycopy(c,0,c1,0,index); 59 System.arraycopy(c,index,c1,index+n,c.length-index); 60 61 } 62 a1 = getElement(); 63 for(int i=0;i<n;i++) { 64 c1[index+i]=a1[i]; 65 } 66 return c1; 67 } 68 69 //打印结果 70 public static void print1(String[] c1) { 71 for(int i=0;i<c1.length;i++) { 72 System.out.print(i+":"+c1[i]+" "); 73 } 74 System.out.println(); 75 } 76 77 //获取需要插入的元素 78 public static String[] getElement() { 79 Scanner b1 = new Scanner(System.in); 80 System.out.println("请输入需要插入的元素(注意空格):"); 81 String a = b1.nextLine(); 82 String[] a1 = a.split(" "); 83 return a1; 84 } 85 }
原文:https://www.cnblogs.com/Trista-ddt/p/10588644.html