public static void main(String[] args) {
Integer b=new Integer(10);
add(b);
System.out.println(b.intValue());
}
static void add(Integer b){
int i=b.intValue();
i+=3;
b=new Integer(i);
}
我认为应该是13,因为add方法传递的是一个引用,在函数中改变了值,在其他方法中用时值也就变了
Integer b=new Integer(10);
add(b);
System.out.println(b.intValue());
}
static void add(Integer b){
int i=b.intValue();
i+=3;
b=new Integer(i);
}
我认为应该是13,因为add方法传递的是一个引用,在函数中改变了值,在其他方法中用时值也就变了
你在add方法中重新new了一个Integer赋值给b,但是java中都是传值调用的,你修改了add方法中的b的指向到了新的Integer,
但是并没有修改main方法中的b的指向。
你如果要修改mian中的不的值,那么你就不能重新new一个Integer而是直接修改b的int值,但是很可惜,Integer并没有提供set方法可以修改Integer的int值,
所以你如果要能够修改里面的值,你只能自己写一个类,比如:
public Class MyInteger{
private int intValue; private void MyInteger(int intValue){
this.intValue = intValue;
}
public int getIntValue(){
return intValue;
}
public void setIntValue(intValue){
this.intValue = intValue;
}
}
public static void main(String[] args) {
Integer b=new MyInteger(10);
add(b);
System.out.println(b.intValue());
}
static void add(MyInteger b){
int i=b.getIntValue();
i+=3;
b.setIntValue(i);
} 这样你的结果就会是13了
你可以把方法里的b 改成m 就很容易知道了! static void add(Integer b){
int i=b.intValue();
i+=3;
b=new Integer(i);
}