java - 增强的 for 循环变量在 java 中的作用域是什么?
问题描述
Java 中不同类的增强型 for 循环 (EFL) 变量的范围是否不同?
ArrayList
当我在包含s上使用 EFL 时,Integer
我无法直接修改它们的值,但是如果我对下面代码中定义的ArrayList
of SimpleObject
s 执行相同的操作,我可以毫无问题地更改实例变量的值。
import java.util.ArrayList;
class SimpleObject{
public int x;
public SimpleObject() {
this.x = 0;
}
}
public class Simple {
public static void main(String args[]){
// Create an arraylist of Integers and SimpleObjects
ArrayList<Integer> intList = new ArrayList<Integer>();
ArrayList<SimpleObject> soList = new ArrayList<SimpleObject>();
// Add some items to the arraylists
intList.add(1);
intList.add(2);
soList.add(new SimpleObject());
soList.add(new SimpleObject());
// Loop over the arraylists and change some values
for (Integer _int : intList) {
_int = 3; // Why doesn't this work but so.x = 5 below does?
}
for(SimpleObject so : soList) {
so.x = 5;
}
// Loop over the arraylists to print out values
for (Integer _int : intList) {
System.out.println("integer = " + _int);
}
for(SimpleObject so : soList) {
System.out.println(" x = " + so.x);
}
}
}
实际输出:
integer = 1
integer = 2
x = 5
x = 5
预期输出:
integer = 3
integer = 3
x = 5
x = 5
所以我的问题是为什么不_int = 3;
坚持第一个 EFL,但坚持so.x = 5;
第二个 EFL?
解决方案
Java 中不同类的增强型 for 循环 (EFL) 变量的范围是否不同?
for
否。在循环或扩展循环中声明的变量的范围是for
循环体。
为什么不 _int = 3; 坚持第一个 EFL,但 so.x = 5;在第二个 EFL 中呢?
在第二个示例中,您没有分配给循环变量so
。
您分配给so.x
. 那是so
变量引用的对象的一个字段。
然后稍后您再次遍历列表并访问您之前更新的对象。
两个循环中的so
变量是不同的变量。
推荐阅读
- node.js - .map() 中的嵌套异步函数无法在 .then() 块之前运行
- php - Wordpress 自定义帖子类型分页 - /page/2/ 未找到
- python - 将列表添加到组合
- c++ - 需要帮助编写一个函数来检查两个 BST 是否具有相同的结构
- vue.js - 更改 v-for 列表后如何重新渲染我的 vue 模板?
- algorithm - 运行最大流算法后,在流网络中找到所有处于某个最小切割中的边
- for-loop - WMIC lastmodified 包含在 for 循环中
- android - 如何检测某个库的使用位置/删除未使用的库
- html - 为什么新元素默认出现在页面顶部?
- c++ - 如何初始化静态输出参数