![](/img/trans.png)
[英]How can I change the value of a variable from inside an ActionListener in Java?
[英]How can I change the value of a variable from inside a method?
我正在尝试创建一种增加各种变量的值的方法,这是我当前正在使用的逻辑类型的示例,但是当该方法完成后,原始变量没有更改。 我需要添加或替换哪些值才能在方法外更改值?
static int num = 2;
static String text = "3";
public static void up(int i, String s){
//Debug
System.out.println("Before Change");
System.out.println("I: " + i);
System.out.println("S: " + s);
System.out.println("Num: " + num);
System.out.println("Text: " + text);
//Code
i = i + 3;
s = String.valueOf(i);
//Debug
System.out.println("After Change");
System.out.println("I: " + i);
System.out.println("S: " + s);
System.out.println("Num: " + num);
System.out.println("Text: " + text);
}
public static void main(String[] args) {
up(num, text);
//Debug
System.out.println("Out of Scope");
System.out.println("Num: " + num);
System.out.println("Text: " + text);
}
您要传递给函数的int i
和String s
是按值传递的 。 这意味着您仅收到变量的副本。 对变量执行的操作不会影响其原始值。
您可以修改您的方法,并使其返回包含修改后的值的对象:
创建一个新类来封装修改后的值:
class Result{
int i;
String s;
public Result(int i, String s){
this.i = i;
this.s = s;
}
}
现在您的方法可以返回此Result
public static Result up(int i, String s){
//Code
i = i + 3;
s = String.valueOf(i);
return new Result(i, s);
}
然后,您可以在main方法中访问修改后的值:
public static void main(String[] args) {
Result r = up(num, "test");
System.out.println("int result " + r.i);
System.out.println("string result " + r.s);
}
您只需在调用方法up(int i, String s)
时传递变量i
的副本值,它将不会更改方法up
的值。
阅读这篇文章: Java是“按引用传递”还是“按值传递”?
您可以使用WrapperClass做到这一点。 这是因为Java像其他提到的那样使用了按值传递。 解决方法是,如果有多个值,则创建WrapperClass。 这是使用WrapperClass修改类的方法。 使用Corba Java框架时,请提供Holder类以提供参考语义。
static int num = 2;
static String text = "3";
public static void up(WrapperClass w){
//Debug
System.out.println("Before Change");
System.out.println("I: " + w.i);
System.out.println("S: " + w.s);
System.out.println("Num: " + num);
System.out.println("Text: " + text);
//Code
w.i = w.i + 3;
w.s = String.valueOf(w.i);
//Debug
System.out.println("After Change");
System.out.println("I: " + w.i);
System.out.println("S: " + w.s);
System.out.println("Num: " + num);
System.out.println("Text: " + text);
}
public static void main(String[] args) {
WrapperClass w = new WrapperClass();
w.i = num;
w.s = text;
up(w);
//Debug
System.out.println("Out of Scope");
System.out.println("Num: " + w.i);
System.out.println("Text: " + w.s);
}
static class WrapperClass {
public int i;
public String s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.