public class StrChTest { String str="good"; char[] ch=new char[]{'n','i','g','h','t'}; public static void main(String[] args) { StrChTest sc=new StrChTest(); sc.changed(sc.str, sc.ch); System.out.print(sc.str+"````"+Arrays.toString(sc.ch)); } public void changed(String stsr,char[] chs) { stsr="love"; chs[0]='i'; } } String和char[]都是引用类型,那为什么str没被改变,ch数组打印出来被改变了呢?! 我画了一个图来说明问题: 1,刚进入sc.changed(sc.str, sc.ch)时,stsr 和 str 的值内容都是good的地址,ch 和 chs 都是指向'n'。 2, stsr="love"; 这句之后str还是指向good,stsr指向love(又产生了新对象),所以stsr没有改变。过程如图数字标识。当执行到chs[0]='i';时,将n改变为i,是将老对象的值改变了,所以在chs消亡后,ch指向的对象也变了。 |
123.jpg (137.16 KB, 下载次数: 4)
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |