Java-数组 给数组增加/删除元素
注:数组一旦被初始化,就没有办法改变他的长度
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);
}
3、数组删除元素
int[] ordArray = {1,2,3,666,4,5,6,7};
int[] newArray=new int[7];
for(int i=0;i<=newArray.length-1;i++){
if (i<3){
newArray[i] = ordArray[i];
}else if (i>=3){
newArray[i] = ordArray[i+1];
}
}
//System.out.println(Arrays.toString(newArray));
for (int X:newArray){
System.out.println(X);
}