注:数组一旦被初始化,就没有办法改变他的长度
1、末尾增加元素
int[] ordArray = {1,2,3,4,5}; int[] newArray = new int[ordArray.length+1]; for (int i=0;i<=ordArray.length-1;i++){ newArray[i]=ordArray[i]; } newArray[newArray.length-1]=0; for (int x:newArray){ System.out.println(x); }
2、指定位置添加元素
int[] ordArray = {1,2,3,4,5}; int[] newArray = new int[ordArray.length+1]; for (int i=0;i<=newArray.length-1;i++){ if (i<3){ newArray[i]=ordArray[i]; }else if (i==3){ newArray[i]=0; }else if (i>3){ newArray[i]=ordArray[i-1]; } } for (int x :newArray){ System.out.println(x); }