简体   繁体   English

Java计算的意外结果

[英]Unexpected result of java calculations

As a result of the following snipet, i got "1 0 1", but i don't know why, im expecting "1 1 1" as a result. 由于下面的片段,我得到了“ 1 0 1”,但是我不知道为什么,我希望结果是“ 1 1 1”。 please can anyone explain to me how things go arround 请任何人能向我解释情况如何

public class Qcb90 {
int a;
int b;
public void f() {
    a = 0;
    b = 0;
    int[] c = { 0 };
    g(b, c);
    System.out.println(a + " " + b + " " + c[0] + " ");
}
public void g(int b, int[] c) {
    a = 1;
    b = 1;
    c[0] = 1;
}
public static void main(String[] args) {
    Qcb90 obj = new Qcb90();
    obj.f();
}
}

Change 更改

b = 1;

to

this.b = 1;

The way you have it now, you are changing the parameter (local) variable not the class member variable. 现在,您正在更改参数(局部)变量而不是类成员变量。

It is because int is not a reference object, for example it is not the object which is created by the word new , so inside the method when you pass b to the method, a new variable will be created for this, and it can just be valid in this method. 这是因为int不是引用对象,例如,它不是由单词new创建的对象,因此,在方法内部,当您将b传递给方法时,将为此创建一个新变量,它可以在此方法中有效。 If an Object that is created by the word new , then it will got affect if it changed by any other method. 如果一个由单词new创建的对象,则通过任何其他方法对其进行更改都会对其产生影响。

The parameter named b in function g(int b, int[] c) hides the class member variable b , so you are setting a local parameter called b to 1 in g(int b, int[] c) . 函数g(int b, int[] c)名为b的参数隐藏了类成员变量b ,因此您要在g(int b, int[] c)中将名为b的局部参数设置为1。 This doesn't affect the member variable at all, and the new value is discarded after g exits. 这根本不影响成员变量,并且g退出后,新值将被丢弃。

However, the local parameter c is a copy of the pointer to the memory that was allocated in f , so you can modify the contents memory since both copies of the pointer (the copy passed in as a parameter to g and also the original in f ) point to the same block of memory. 但是,局部参数c指向 f中分配的内存的指针的副本,因此您可以修改内容内存,因为指针的两个副本(作为参数传递给g的副本,还包含f的原始指针) )指向同一块内存。

  public class Qcb90 {
    int a;
    int b;
    public void f() {
        a = 0;
        b = 0;
        int[] c = { 0 };
        g(b, c);
    // so here b is your instance variable
        System.out.println(a + " " + b + " " + c[0] + " ");
    }
    public void g(int b, int[] c) {
        a = 1;
        //b = 1;  this b is a parameter of your method 
this.b=1; //now run your program


        c[0] = 1;
    }
    public static void main(String[] args) {
        Qcb90 obj = new Qcb90();
        obj.f();
    }
    }

If you want to print b value you need to write this.b inside g() 如果要打印b值,则需要在g()写入this.b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM