1.跟Integer和int没关系,你这个程序中在main方法里面定义了局部对象Integer,所以打印出来的是局部变量的值,你变成int同样是这样。 2.你如果把 Integer g 放在main方法的外面,eclipse会提示要变成static才合理。 package csdn.programbbs_530; //输出:10 100 public class Test { public static void main(String[] args) { Integer g = 10; f(g); System.out.println(g); int a = 100; g(a); System.out.println(a); } private static void f(Integer g) { g = 30; } private static void g(int a) { a = 300; }}
这个跟你的程序写错了有关,用一个错误的问题是不可能得到一个正确的答案的。可以变成: package csdn.programbbs_530; /* * 输出:30 300 */ public class Test { public static void main(String[] args) { Integer g = 10; g = f(g); System.out.println(g); int a = 100; a = g(a); System.out.println(a); } private static Integer f(Integer g) { return g = 30; } private static int g(int a) { return a = 300; }}
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}这是源码,赋值的时候调的是这个方法,返回值是新new出来的对象
再把新实例的对象赋给他。
也就是我们不能像其他的对象一样传递引用改变他的值。Integer是引用类型,是int型数据的包装类。实质上,你说的是对的,当执行g=30的时候,会先在栈里查找30,如果有,返回这个对象x,如果没有,则创建,然后返回对象x,最终g指向x的地址。
等价于
g = new Integer(30); 自动装包这个时候方法f里面的g指向的地址和main里面的g指向的地址已经不一样了。
无论你怎么在f函数里面改变,Main函数里面的g永远指向10。你又没有改变Main函数里面的g指向的对象。
你不妨输出f(g)试试。应该是30无误。或者Main中f(g)改为g=f(g),这样也能输出30。
2.你如果把 Integer g 放在main方法的外面,eclipse会提示要变成static才合理。
package csdn.programbbs_530;
//输出:10 100
public class Test {
public static void main(String[] args) {
Integer g = 10;
f(g);
System.out.println(g); int a = 100;
g(a);
System.out.println(a);
} private static void f(Integer g) {
g = 30;
} private static void g(int a) {
a = 300;
}}
package csdn.programbbs_530;
/*
* 输出:30 300
*/
public class Test {
public static void main(String[] args) {
Integer g = 10;
g = f(g);
System.out.println(g); int a = 100;
a = g(a);
System.out.println(a);
} private static Integer f(Integer g) {
return g = 30;
} private static int g(int a) {
return a = 300;
}}
// TODO Auto-generated method stub
anotherG=30;
}
把你的函数的参数改了个名字,便于描述
当开始调用f(g)的时候,形参anotherG 和 main中的变量g指向了同样的对象 Integer(10)
当调用anotherG=30的时候, 新建了一个对象Integer(30),让形参anotherG 指向了它
原来那个变量g没有任何改变,所以还是10
只要在函数里面用new给形参赋值
都会出现那种情况
所有的引用类型都是
关键要理解f()函数g是一个局部变量,而最终打印的是Integer g = 10这里定义的g。
要想得到结果,改写f,然后赋值g= f(g)。