今天继续坚持阅读了一篇英文版技术帖子,一如既往地艰难,感觉每天新学那么几个单词远远不足以填补我对英语的需求,看来距离能从容阅读许多框架官网文档的目标依旧遥遥无期。
先把代码贴出来:
public static void change(String x) { x = "cd"; } public static void main(String[] args) { String x = new String("ab"); change(x); System.out.println(x); }
最终输出结果为ab,实际上并不难理解,只可惜我初看时也陷入了一种思维定式,基本数据类型传递内容,引用数据类型传递引用,也就是内存地址。
也就是说,如果传入方法的是一个基本数据类型,那么实际上传入的是这个基本数据类型的一个副本,不论程序怎么蹂躏它都和原本的数据没有关系。
而引用数据类型传参的时候就有些不同了,因为传递进来的是对象的引用,操作这个引用,就相当于改变了存储在堆中原本的对象,然而我忽视了一点,即便是引用数据类型传参传递进来的也是副本。
直接操作形参变量的话与原本的变量也是没有关系的,实际上并没有改变原本变量中存储的引用。
所以,代码出现这个现象也就不难理解了。
感觉犯了一个不该犯的错误... ...居然会被这种问题迷惑... ...