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);
这两个是不同的对象。。。。。尽管他们的内容是一样的。。。
就像有两个人。。。他们的名字是相同的。。。。但是并不是一样的人。。。。
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);
这两个是不同的对象。。。。。尽管他们的内容是一样的。。。
就像有两个人。。。他们的名字是相同的。。。。但是并不是一样的人。。。。
相关文章推荐
- Android中为你的应用程序添加桌面快捷方式
- 精华阅读第6期|程序猿的世界,你不懂!
- 开始我的第一篇文章 vector容器的源码解析
- PHP Redis安装和使用
- 【杭电oj】2084 - 数塔(动态规划)
- 1003. Emergency (25)
- [nodejs] 格式化日期、ejs模板引擎改变.ejs为.html、mongoose查询所有
- Android Art Hook 技术方案
- iOS-BLE蓝牙开发持续更新
- windows系统下Python环境的搭建
- 一些技术大牛的博客集锦(转)
- 如何去除NavigationView中menu的scrollbar? 解决办法
- Generate a Push Certificate
- mac 安装 CouchDB
- listview的item中含有button导致onitemclick事件失效的解决方法
- setOnclickable(false) 不起作用
- Android ViewPager图片适配
- QT下面的中文乱码问题
- CoreDate入门
- 如何快速截取某段时间内的日志