您的位置:首页 > 其它

New误解

2016-03-07 18:07 218 查看
问题:

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);

这两个是不同的对象。。。。。尽管他们的内容是一样的。。。

就像有两个人。。。他们的名字是相同的。。。。但是并不是一样的人。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: