首页 > 代码库 > 【JAVA】for,foreach遍历数组时候一些区别

【JAVA】for,foreach遍历数组时候一些区别

public class ArrayTest {
	static public void incr(int a[]) {
		for (Integer i : a) {
			i += 1;
		}
	}
	static public void incr1(int a[]) {
		for (int i = 0, len = a.length; i < len; i++) {
			// a[i] = a[i] + 1;
			a[i]++;
		}
	}
	static public void main(String args[]) {
		int a[] = { 1, 2, 3, 4, 5 };
		for (int i : a)
			System.out.print(i + " ");
		System.out.println("\nforeach result:");
		incr(a);
		for (int i : a)
			System.out.print(i + " ");
		System.out.println("\n");
		int b[] = { 1, 2, 3, 4, 5 };
		for (int i : b)
			System.out.print(i + " ");
		System.out.println("\nfor loop result:");
		incr1(b);
		for (int i : b)
			System.out.print(i + " ");
	}
}

output:

1 2 3 4 5 
foreach result:
1 2 3 4 5 


1 2 3 4 5 
for loop result:
2 3 4 5 6 


foreach遍历的时候,相当于将数组中的值赋给相应的变量,所以对于 int array foreach循环,内部的修改不会影响原数组的值。