New误解

来源:互联网 发布:淘宝有库存管理吗 编辑:程序博客网 时间:2024/05/18 01:38
问题:
public class ckeef


{  public static void main(String args[])


    {  String s1,s2,s3,s4;


       s1=new String("we are students");


       s2="We are students";
       s3="We are students";


s4=new String(s1);


System.out.println(s1.equals(s2));    


       System.out.println(s3==s2);         //s2和s3为什么是对的??


       System.out.println(s1.equals(s4));    


       System.out.println(s1==s4);       //s1和s4的引用不是一样的么?为什么输出的是false??


    }


}


答案:
这个确实是容易引起混乱的。。。让人疑惑的。。。


关键在于。。。你要理解s1=new String("we are students");
 s2="We are students";
这两个是不一样的。。。。new是用新建一个对象的方法。。。。而后一种是放在常量池中的。。。你一下次再用这种方法去创建的时候。。。就会去常量池里面找,所以
s2="We are students";
       s3="We are students";


这两个是相同的。。。指向常量池中的"We are students";。。。


而s1=new String("we are students");
       s4=new String(s1);
这两个是不同的对象。。。。。尽管他们的内容是一样的。。。
就像有两个人。。。他们的名字是相同的。。。。但是并不是一样的人。。。。
0 0
原创粉丝点击