【问题标题】:Scope of variable in Java for Array vs non-array Object [duplicate]Java中数组与非数组对象的变量范围[重复]
【发布时间】:2017-10-01 06:45:23
【问题描述】:

我试图理解为什么输出值会在 Array 的情况下发生变化,而不是在 object 的情况下。

public class SameClass {
  private Integer a;
  private Integer b[];
  public SameClass(Integer a) {
    this.a=a;
  }
  public SameClass(Integer a, Integer b[]) {
    this.a=a;
    this.b=b;
  }
  public static void main(String args[]) {
    Integer a = new Integer(5);
    Integer b[] = {2,5};
    // create two different objects
    SameClass sam = new SameClass(a);
    SameClass samB = new SameClass(a,b);
    //change values in local variables
    a=7;
    b[0]= 8;
    //print values 
    System.out.println(sam.a);
    System.out.println(samB.b[0] + " " + samB.a);
  }
}

这段代码的输出是:

5
8 5

【问题讨论】:

  • 提示:a=7 等价于 a = new Integer(7)

标签: java variables object scope


【解决方案1】:
//change values in local variables
a=7;
b[0]= 8;

您的评论是错误的:您没有更改局部变量b 中的值。您更改了b 指向的数组中一个槽的值,并且从您的对象中引用了相同的数组。这就是为什么a = 7 对您的对象没有影响,而b[0] = 8 会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2011-11-03
    • 2023-03-20
    • 2020-04-23
    • 2013-03-06
    • 2015-02-17
    • 2018-07-31
    相关资源
    最近更新 更多