java 方法传值浅拷贝验证

时间:2023-01-16 13:04:01

source code

import org.junit.Test;

public class SigmoidTruncatedSuit {
@Test
public void main_test() {
Float xs = 3f;
System.out.println(String.format("Float origin : %s",xs));
convert(xs);
System.out.println(String.format("Float convert : %s",xs));
java.util.HashMap<Integer, Float> m = new java.util.HashMap<>();
m.put(0,1f);
System.out.println(String.format("HashMap origin : %s",m.get(0)));
cct(m);
System.out.println(String.format("HashMap convert : %s",m.get(0)));
}
public void convert(Float x) {
System.out.println(String.format("Float inner origin : %s",x));
x = 13f;
System.out.println(String.format("Float inner convert : %s",x));
}
public void cct(java.util.HashMap<Integer, Float> m){
System.out.println(String.format("HashMap inner origin : %s",m.get(0)));
m.put(0,13f);
m = new java.util.HashMap<>();
System.out.println(String.format("HashMap inner convert : %s",m.get(0)));
}

output

Float origin : 3.0
Float inner origin : 3.0
Float inner convert : 13.0
Float convert : 3.0
HashMap origin : 1.0
HashMap inner origin : 1.0
HashMap inner convert : null
HashMap convert : 13.0

结论

  • Java方法参数传递为值传递
  • Java方法值传递为浅拷贝
  • Scala 类似