论坛首页 Java版

很简单的==和equal的问题

浏览 16097 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
最后更新时间:2005-03-22
都知道
[code:1]String a = "abc";
String b = "abc";
a==b;//true
a.equal(b);//true[/code:1]
那这样呢
[code:1]String a = "abc";
String b = "ab";
String c = b + "c";
a==c?//true or false[/code:1]
大家别笑偶阿。。
   
最后更新时间:2005-03-22
"+"导致生成新的string
所以结果是false
   
0 请登录后投票
最后更新时间:2005-03-22
[code:1]
String a = "abc";
String b = "ab";
String c = (b + "c").intern();
a==c//true
[/code:1]
这样就不一样了,那位兄弟能具体给讲解一下?
   
0 请登录后投票
最后更新时间:2005-03-22
fishbob 写道
[code:1]
String a = "abc";
String b = "ab";
String c = (b + "c").intern();
a==c//true
[/code:1]
这样就不一样了,那位兄弟能具体给讲解一下?


这个问题文档中很清楚啊


引用

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
   
0 请登录后投票
最后更新时间:2005-03-22
swing 写道
"+"导致生成新的string
所以结果是false



String a = "ab";
String b = "a" + "b";
a == b ;//true or false;
   
0 请登录后投票
最后更新时间:2005-03-22
推荐: 关于Java栈与堆的思考

http://soft.yesky.com/SoftChannel/72342371961929728/20050218/1912444.shtml
   
0 请登录后投票
最后更新时间:2005-03-22
Morgan0916 写道
推荐: 关于Java栈与堆的思考

http://soft.yesky.com/SoftChannel/72342371961929728/20050218/1912444.shtml


我想这个文章是有问题的。
引用
String str = "abc"……在栈中查找有没有存放值为"abc"的地址……

这句话摆明就是瞎说。Java语言规范12.5节:
引用
A new class instance may be implicitly created in the following situations:
    * Loading of a class or interface that contains a String literal (§3.10.5) may create a new String object to represent that literal. (This might not occur if the same String has previously been interned (§3.10.5).)

也就是说,String str = "abc"跟String str = new String("abc")是一样的,都是new一个String对象。唯一的区别在于,在第一种情况下,JVM可以把value为"abc"的String对象保存起来,下次遇到String str2 = "abc"的时候不必重新new一个。这里根本就没有什么栈什么堆的事,顶多有个静态常量区。

另外这两句话:
引用
[在Java中]栈的优势是,存取速度比堆要快

引用
如int a = 3; 这里的a是一个指向int类型的引用,指向3这个字面值。这些字面值的数据,由于大小可知,生存期可知(这些字面值固定定义在某个程序块里面,程序块退出后,字段值就消失了),出于追求速度的原因,就存在于栈中。

我也觉得很可疑,不过在spec上没有翻到。
   
0 请登录后投票
最后更新时间:2005-03-22
Morgan0916 写道
推荐: 关于Java栈与堆的思考

http://soft.yesky.com/SoftChannel/72342371961929728/20050218/1912444.shtml



不知道为什么会有那么多人混淆对象和引用、栈和堆的差别。不想多解释,只想指出这篇文章漏洞百出。

建议阅读:
1.《Effective Java》
2. 《深入Java虚拟机》(如果细读effective java,其实也不必看《深入》)
   
0 请登录后投票
最后更新时间:2005-03-22
SCJP中有讲到这个问题。
   
0 请登录后投票
最后更新时间:2005-03-23
java 中的String 有点特殊 与其他类有点不同。。。 好像 sun 认为 String 的处理比较多 所以作了一点  优化吧。。
//jdk1.4
String a="ab";
String b="ab";
a==b // true;

String a=new String("ab");
String b=new String ("ab");
a==b //false;

搂住的 问题 可能与这个有关
   
0 请登录后投票
论坛首页 Java版

跳转论坛:
JavaEye推荐