一、需求
通过方法对对象进行赋值,期望到方法外之前的赋值依然生效。
二、Java传值与传址
public static void main(String[] args) {
int x = 0;
// 1.传值调用
System.out.println("1.原本的值:" + x);
setValue(0);
System.out.println("1.使用传值方法后x的值:" + x);
int[] xs = new int[]{0};
// 2.传址调用
System.out.println("2.原本的值:" + xs[0]);
setValueByAddr(xs);
System.out.println("2.使用传址方法后x的值:" + xs[0]);
}
/**
* 传值
*
* @param x
*/
public static void setValue(int x){
x = 1;
}
/**
* 传址
*
* @param xs
*/
public static void setValueByAddr(int[] xs){
xs[0] = 1;
}
三、结论
java中在方法内直接对对象进行复制是没用的!但可以通过数组的形式获取到对象的地址,然后在通过xs[0] = 1的形式进行赋值!