修改形参对象值,会影响实参

这个问题是在写工具类的时候碰到的,
有时候为了方便,直接操作形参,可能会导致函数外实参的改变,
然后bug就这样诞生了

1
2
3
4
5
6
7
Timestamp now = new Timestamp(System.currentTimeMillis());
System.out.println("now:: " + now.toString());
Timestamp nextTime = DateUtils.getNextTime(now, Calendar.MONDAY, 2, 12, 23, 31, TaskTypeEnums.EVERY_MONTH.getCode());

System.out.println("now after:: " + now.toString());
// 周一,2号,12:23:31,每月
System.out.println("nextTime:: ="+nextTime.toString());

打印出来的结果是

1
2
3
now:: 2018-07-21 13:52:29.2
now after:: 2018-07-02 12:23:31.2
nextTime:: =2018-07-02 12:23:31.2

提供一段伪代码

当形参是对象时,形参指向的是实参的堆地址值,直接在函数中操作形参自然会影响到实参
但是,当形参是基础类型时,实参值不受影响

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Class Monitor{
private String cpuUsed;
String getCpuUsed(){
return cpuUsed;
}
}

main(){
int flag = 2;
Monitor a = new Monitor();
flagObject.setCpuUsed("11");

System.out.println("before::flag:: "+flag+",a:: "+a.getCpuUsed());

aaa(flag,a);

System.out.println("after::flag:: "+flag+",a:: "+a.getCpuUsed());

}

public static void aaa(int a, Monitor a1){
a+=1;
a1.setCpuUsed("22");

}

结果

1
2
before::flag:: 2,a::11 
after::flag:: 2,a::22