关于string类中intern方法的提问

fengzhizi715 2004-11-24 03:29:10

/**
* Created by IntelliJ IDEA.
* User: fengzhizi
* Date: 2004-11-22
* Time: 23:28:20
* To change this template use Options | File Templates.
*/
import javax.swing.*;

public class StringIntern {
public static void main(String args[])
{
String s1,s2,s3,s4,output;

s1=new String("hello");
s2=new String("hello");

if(s1==s2)
output="s1 and s2 are the same object in memory";
else
output="s1 and s2 are not the same object in memory";

if(s1.equals(s2))
output+="\ns1 and s2 are equal" ;
else
output+="\ns1 and s2 are not equal" ;

s3=s1.intern();
s4=s2.intern();

if(s3==s4)
output+="\ns3 and s4 are the same object in memory" ;
else
output+="\ns3 and s4 are not the same object in memory" ;

if(s1==s3)
output+="\ns1 and s3 are the same object in memory";
else
output+="\ns1 and s3 are not the same object in memory";

if(s2==s4)
output+="\ns2 and s4 are the same object in memory";
else
output+="\ns2 and s4 are not the same object in memory";

if(s1==s4)
output+="\ns1 and s4 are the same object in memory";
else
output+="\ns1 and s4 are not the same object in memory";

JOptionPane.showMessageDialog(
null,output,"Demonstrating String Method intern",
JOptionPane.INFORMATION_MESSAGE);

System.exit(0);
}
}


以上这个程序是Java How To Program中关于string类中的一个函数
看了书上的注解,但是我始终不太理解intern方法如何正确使用。
为何s3==s4
而s1!=s3
...全文
111 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuyuestar 2004-11-24
  • 打赏
  • 举报
回复
S3,S4的intern()方法把新建的String对象放到了缓冲池里,这样s3和s4就引用了同样的对象了,都是指向缓冲池中的"hello",因此这两个引用是相等的.
而s1=new String("hello");不使用缓冲池中的对象,是重新new出来的,因此S1和S4引用的是两个不同的对象,所以不等...

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧