java传值问题?
public class Demo{
public static void main(String[] args) {
int a = 1;
Integer b = new Integer(1);
Method1(a, b);
System.out.println(a);
System.out.println(b);
}
public static void Method1(int a, Integer b) {
a = 1000;
b = 1000;
}
}
我理解a的值不会变,但是为什么b的值也不变呢?
回复
1个回答

test
2024-07-20
传参等同于赋值,原代码等同于
public class Demo {
public static void main(String[] args) {
int a = 1;
Integer b = new Integer(1);
int _a = a;
Integer _b = b;
_a = 1000;
_b = 1000;
System.out.println(a);
System.out.println(b);
}
}
修改的是 _a
,_b
这两个参数,a
,b
不受影响
所以 java 无法在方法里修改外部的局部变量,代替的做法是:修改数组元素、对象属性、类属性
public class Demo {
static int c;
public static void main(String[] args) {
int[] a = new int[] { 1 };
MutableInt b = new MutableInt(1);
c = 1;
Method1(a, b);
System.out.println(a[0]);
System.out.println(b.value);
System.out.println(c);
}
public static void Method1(int[] a, MutableInt b) {
a[0] = 1000;
b.value = 1000;
c = 1000;
}
}
class MutableInt {
int value;
public MutableInt(int value) {
this.value = value;
}
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容