渔人码头

天行健,君子以自强不息。地势坤,君子以厚德载物。
posts - 12, comments - 16, trackbacks - 0, articles - 43
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

intern()得到的String之间的==

Posted on 2007-03-11 21:09 Fisher 阅读(457) 评论(0)  编辑  收藏 所属分类: Java 学习笔记
String s1="abc"; // 这种形式的字符串,被保存在常量池中
String s2=new String("abc"); // 用new生成的字符串,保存在堆中
关于intern()方法,见下列说明:
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.
综上,解决你的第三个问题:
String s1=new String("abc");     // s1指向的是堆中的地址
String s2=new String("abc").intern();  // s2指向的是常量池中的地址
System.out.println(s1==s2) ;    // 地址根本就不同,自然s1==s2为false"

 

        String aaa = new String("aaa");
        String aaa2 
= new String("aaa").intern();
        
        System.out.println(aaa 
== aaa2);//false
        System.out.println(aaa == "aaa");//false
        System.out.println(aaa2 == "aaa");//true

只有注册用户登录后才能发表评论。


网站导航: