1 package day07_addition; 2 import java.util.Arrays; 3 import java.util.Random; 4 5 //数组 伸缩、增删、位移、复制 6 public class ArrayFounderTrans { 7 public static void main(String[] args){ 8 int[] a = new int[6]; 9 Random rand = new Random(); 10 11 //初始化数组a[] 12 for(int i=0;i<a.length;i++){ 13 a[i] = (int)(rand.nextInt(100)); /* a[i] = (int)(Math.random()*100); */ 14 System.out.print(a[i]+" "); 15 } 16 System.out.println(); 17 18 /* 19 * 20 //数组缩进a[6]-->a[5] 21 a = Arrays.copyOf(a, 5); 22 for(int i=0;i<a.length;i++){ 23 System.out.print(a[i]+","); 24 } 25 */ 26 27 System.out.println("去掉第3个因素"); 28 29 //方法1 复制:复制第4个元素及后面的元素,实现删除第3个元素 30 int[] a1 = new int[5]; 31 int n = 3; 32 System.arraycopy(a, 0, a1, 0, n-1); 33 System.arraycopy(a, n, a1, n-1, a.length-n); 34 for(int i=0;i<a1.length;i++){ 35 System.out.print(a1[i]+" "); 36 } 37 38 /* 39 * 40 //方法2 数组按位交换,然后去掉最后元素,实现删除目标元素 41 int temp; 42 43 44 //从第3个元素开始移位 45 for(int i=3;i<a.length-1;i++){
47 temp = a[i];
a[i] = a[i+1];
a[i+1] = temp; 48 } 49 */ 50 } 51 }
数组伸缩