关于lambda表达式访问外部变量有一个非常重要的限制的一点疑惑
lambda表达式访问外部变量有一个非常重要的限制:变量不可变。
请问为什么:
String[] array = {"a", "b", "c"};
for(Integer i : Lists.newArrayList(1,2,3)){
Stream.of(array).map(item -> Strings.padEnd(item, i, '@')).forEach(System.out::println);
}可以执行呢?
而:
String[] array = {"a", "b", "c"};
for(int i = 1; i<4; i++){
Stream.of(array).map(item -> Strings.padEnd(item, i, '@')).forEach(System.out::println);
}就不可以?这两个i都是局部变量,并且不是final呀?
难道说在lambda语句执行过程中不可变就可以了吗?我觉得不太对,我查了一些for each的源代码,是不是因为第一个里的i指向的是迭代器里的next方法返回的对象这是不变的,而根据
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
next方法返回的对象是改变的。所以临时变量i是final的。
不知道理解的对不对,希望各位大神可以指点一下,谢谢