java数组:数组增加元素

例1:

在一个数组{1,2,3,4,5,6,7}后面加一个 0 :

package cn.xtnotes.u6;

public class T5 {

	public static void main(String[] args) {
		// 数组一旦初始化 长度无法改变
		 //在数组后加一个0
		int[] oldList= {1,2,3,4,5,6,7};
		int[] newList= new int[oldList.length+1];
		
		for(int i=0;i<=oldList.length-1;i++) {
			newList[i]=oldList[i];
		}
		newList[oldList.length]=0;
		for(int x:newList) {
			System.out.println(x);
		}
	}
}

例2:

在一个数组{1,2,3,4,5,6,7}的第三个位置后加一个 0

package cn.xtnotes.u6;
public class T5 {
	public static void main(String[] args) {
		int[] oldList= {1,2,3,4,5,6,7};
         	int[] newList= new int[oldList.length+1];
     	
     	       for(int i=0;i<=newList.length-1;i++) {
     		if(i<2) {
     			newList[i]=oldList[i];
     		}else if(i==2) {
     			newList[i]=0;
     		}else if(i>2) {
     			newList[i]=oldList[i-1];
     		}
     		for(int x:newList) {
    			System.out.println(x);
    		}
		}
	}
}

 

 

阅读剩余
THE END