黑马程序员技术交流社区

标题: String引用类型 [打印本页]

作者: tcny    时间: 2014-3-26 01:18
标题: String引用类型
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)

123.jpg

作者: lwy0319    时间: 2014-3-26 04:25
本帖最后由 lwy0319 于 2014-3-26 04:45 编辑

字符串内容不可更改,属于常量:
  1. public class Text {
  2.          String str="我是专一的情种";
  3.          public void fun(String str){
  4.                  str="我万花丛中过,片叶不沾身";
  5.          }
  6.         public static void main(String[] args){
  7.         Text t=new Text();
  8.         t.fun(t.str);
  9.                 System.out.println(t.str);
  10.         }
  11. }
复制代码



运行结果:我是专一的情种
当然如果你要实在想改也可以改变其在堆内存中的地址指向:
  1. public class Text {
  2.         public static void main(String[] args){
  3.         String str="haha";
  4.         str=str+"hehe";
  5.                 System.out.println(str);
  6.         }
  7. }
复制代码
输出结果:hahahehe
这个时候堆内存中有三个对象,一个为"haha",一个为"hehe",一个为"hahahehe"。






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2