首页 > 解决方案 > 增强的 for 循环变量在 java 中的作用域是什么?

问题描述

Java 中不同类的增强型 for 循环 (EFL) 变量的范围是否不同?

ArrayList当我在包含s上使用 EFL 时,Integer我无法直接修改它们的值,但是如果我对下面代码中定义的ArrayListof SimpleObjects 执行相同的操作,我可以毫无问题地更改实例变量的值。

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?

标签: javaforeach

解决方案


Java 中不同类的增强型 for 循环 (EFL) 变量的范围是否不同?

for否。在循环或扩展循环中声明的变量的范围是for循环体。

为什么不 _int = 3; 坚持第一个 EFL,但 so.x = 5;在第二个 EFL 中呢?

在第二个示例中,您没有分配给循环变量so

您分配给so.x. 那是so变量引用的对象的一个​​字段。

然后稍后您再次遍历列表并访问您之前更新的对象。

两个循环中的so变量是不同的变量。


推荐阅读