一維數組:
public class ArrayDemo {
public static void main(String[] args) {
int arr[]=new int[]{1,2,3,4,5,6};
int newArr[]=Arrays.copyOf(arr,8);
Arrays.fill(arr,2,5,0);
for (int tmp:newArr) {
System.out.println(tmp);
}
}
這是一個數組替換以及foreach用法結合。
for(元素類型type 元素變量value :遍歷對象obj){
引用x的java語句
}
結果:
1
2
3
4
5
6
0
0
二維數組:
public class ArrayDemo {
public static void main(String[] args) {
int arr[][]= new int[][]{{1,2,3},{4,5,6}};
// int newArr[][]=Arrays.copyOf(arr,8);
// Arrays.fill(arr,2,5,0);
for (int tmp[]:arr) {
for (int y:tmp){
System.out.print(y+"、");
}
System.out.println();
}
}
}
結果:
1、2、3、
4、5、6、