更改布尔值?
我对Java中的布尔值有疑问。 假设我有一个这样的程序:
boolean test = false; ... foo(test) foo2(test) foo(Boolean test){ test = true; } foo2(Boolean test){ if(test) //Doesn't go in here }
我注意到在foo2中,布尔测试不会改变,因此不会进入if语句。 那我怎么去换呢? 我查看了布尔值,但我找不到一个将测试从“设置”为true的函数。 如果有人能帮助我,这将是伟大的。
你将一个原始布尔值传递给你的函数,没有“引用”。 所以你只是在你的foo
方法中隐藏价值。 相反,您可能想要使用以下之一 –
持有人
public static class BooleanHolder { public Boolean value; } private static void foo(BooleanHolder test) { test.value = true; } private static void foo2(BooleanHolder test) { if (test.value) System.out.println("In test"); else System.out.println("in else"); } public static void main(String[] args) { BooleanHolder test = new BooleanHolder(); test.value = false; foo(test); foo2(test); }
哪个输出“在测试中”。
或者,通过使用
成员变量
private boolean value = false; public void foo() { this.value = true; } public void foo2() { if (this.value) System.out.println("In test"); else System.out.println("in else"); } public static void main(String[] args) { BooleanQuestion b = new BooleanQuestion(); b.foo(); b.foo2(); }
其中,也输出“在测试中”。
您将参数命名为与实例变量相同。 这里,参数是引用的参数,而不是实例变量。 这称为“阴影”,其中作为参数名称的简单名称test
实例变量,也称为test
。
在foo
,您将参数test
更改为true
,而不是实例变量test
,它未更改。 这就解释了为什么它不会进入foo2
的if
块。
要分配值,请删除foo
上的参数,或使用this.test
引用实例变量。
this.test = true;
和
if (this.test)
您需要注意:
- 在Java中,参数是按值传递的。
- Boolean,boolean的包装类型是不可变的。
由于1和2,您无法更改方法中布尔传递的状态。
你大多有两个选择:
选择1:有一个boolean的可变持有者,如:
class BooleanHolder { public boolean value; // better make getter/setter/ctor for this, just to demonstrate }
所以在你的代码中它应该看起来像:
void foo(BooleanHolder test) { test.value=true; }
选择2:更合理的选择:从您的方法返回值:
boolean foo(boolean test) { return true; // or you may do something else base on test or other states }
调用者应该使用它:
boolean value= false; value = foo(value); foo2(value);
这种方法是优选的,因为它更适合普通的Java编码实践,并且通过方法签名,它给调用者提示它将根据您的输入返回一个新的值。
您的foo
方法将test
的值更改为true。 看起来你想要的是为每个函数使用实例变量。
boolean test = false; ... foo(test) foo2(test) foo(Boolean test){ this.test = true; } foo2(Boolean test){ if(this.test) //Doesn't go in here }
这样,您的方法只会更改该方法内部的test
值,但您的公共test
参数将保留false
值。