java 在java中的类函数中更改布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10161993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing boolean value in class function in java
提问by Global Warrior
Can we modify a Boolean value in class function in java, something like this wont work as the change is local to function. How can we make the following change passed variable reflect outside the method call?
我们可以在 java 中的类函数中修改布尔值吗,这样的事情是行不通的,因为更改是函数本地的。我们如何才能使传递的以下更改反映在方法调用之外?
public void changeboolean(Boolean b)
{
if( somecondition )
{
b=true;
}
else
{
b=false;
}
}
EDIT The code could be like this:
编辑代码可能是这样的:
public String changeboolean(Boolean b,int show)
{
if( somecondition )
{
b=true;
show=1;
return "verify again";
}
else
{
b=false;
show=2;
return "Logout";
}
show=3;
return verifed;
}
I'm searching for something like this
我正在寻找这样的东西
b.setvalue(true);
Is it possible?
是否可以?
回答by Jon Skeet
Can we modify a Boolean value in class function in java
我们可以在java中的类函数中修改布尔值吗
No, Boolean
is immutable, like all the wrappers for the primitive types.
不,Boolean
是不可变的,就像原始类型的所有包装器一样。
Options:
选项:
- Return a
boolean
from your method (best choice) - Create a mutable equivalent of
Boolean
which allows you to set the embedded value. You would then need to modify the value within the instancethat the parameter refers to - changing the value of the parameter to refer to a different instance wouldn't help you, because arguments are always passed by value in Java. That value is either a primitive value or a reference, but it's still passed by value. Changing the value of a parameter never changes the caller's variable. - Use a
boolean[]
with a single element as the wrapper type - Use
AtomicBoolean
as the wrapper type
boolean
从您的方法中返回 a (最佳选择)- 创建一个可变等价物,
Boolean
它允许您设置嵌入值。然后您需要修改参数引用的实例中的值 - 更改参数的值以引用不同的实例对您没有帮助,因为在 Java 中参数总是按值传递。该值要么是原始值,要么是引用,但它仍然是按 value 传递的。改变参数的值永远不会改变调用者的变量。 - 使用
boolean[]
带有单个元素的 a 作为包装器类型 - 使用
AtomicBoolean
的包装类型
回答by kasongoyo
Boolean is immutable, like all the wrappers for the primitive types. Soln: Trying using MutableBoolean of apacheCommon http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html
Boolean 是不可变的,就像原始类型的所有包装器一样。Soln:尝试使用 apacheCommon http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html的 MutableBoolean