Java的引用传递

先看代码:

package pass.value; public class ParameterPassingAsObjectOther { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello "); System.out.println("Before change, sb = " + sb); System.out.println("sb's hasCode: " + sb.hashCode()); changeData(sb); System.out.println("After changeData(n), sb = " + sb); System.out.println("sb's hasCode: " + sb.hashCode()); } public static void changeData(StringBuffer strBuf) { System.out.println("strBuf's hasCode: " + strBuf.hashCode()); StringBuffer sb2 = new StringBuffer("Hi "); System.out.println("sb2's hasCode: " + sb2.hashCode()); strBuf = sb2; sb2.append("World!"); System.out.println("strBuf's hasCode: " + strBuf.hashCode()); } } OUTPUT: Before change, sb = Hello sb's hasCode: 28737396 strBuf's hasCode: 28737396 sb2's hasCode: 6927154 strBuf's hasCode: 6927154 After changeData(n), sb = Hello sb's hasCode: 28737396  

 

 

可见:Java中对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数。如果在方法里形参指向的内存地址改变了(通常为新建了对象,形参并指向了它),并不会影响实参的改变..

参考:http://blog.sina.com.cn/s/blog_4b622a8e0100c1bo.html

你可能感兴趣的:(java,c,String,Class,output)