谁来解释一个intern方法的使用

roastangle 2003-10-21 02:20:18
String类的intern方法我的理解是把String类的字符串加入到一个字符串处理池中以后如果声明同样字符对象像自动从池中把字符对象的指针给新的对象。但我做试验没有成功,也不知道我理解的对不对我的代码如下:
class internDemo
{
public void main(String[] args)
{
String strMsg1=new String("test1").intern();

String strMsg2=new String("test1");

if(strMsg1==strMsg2)
{
System.out.println("==");
}
else
{
System.out.println("!=");
}

}
}
...全文
116 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
roastangle 2003-10-25
  • 打赏
  • 举报
回复
这个问题已经看到了。但是用intern方法后为什么还是不能直接比较引用呢??
tigermaomaolaoliu 2003-10-24
  • 打赏
  • 举报
回复
main前面的限定符是:public static void
roastangle 2003-10-24
  • 打赏
  • 举报
回复
我知道不一样,但是intern的意思不就是在地址池中保留字符对象引用吗??所以我认为第二次new的时候这两个引用应该相等呀??我是想测试这个结论。这是没成功,是不是我对inten方法的理解不对呀??
binny 2003-10-22
  • 打赏
  • 举报
回复
new String("test1")和"test1"可不一样
httruly0 2003-10-22
  • 打赏
  • 举报
回复
public class test {

public test() {
}
public static void main(String[] args) {
String a1 = new String("aaaa").intern();
String a2 = new String("aaaa");
if(a1 == a2)
{
System.out.println("==");
}else if(a1.equals(a2))
{
System.out.println("equal");
}
else{
System.out.println("!=");
}
}
}
输出equal
roastangle 2003-10-22
  • 打赏
  • 举报
回复
还是不行呀。还是运行错误
Exception in thread "main" java.lang.NoSuchMethodError: main
:)一运运intern方法就这样55这是怎么回事呀。
mortal 2003-10-21
  • 打赏
  • 举报
回复
试了一下,那样不行,应该这样才行
String strMsg2=new String("test1").intern();
String strMsg1="test1";

if(strMsg1==strMsg2)
{
System.out.println("==");
}
else
{
System.out.println("!=");
}
intern()方法大概就是你说的这个意思
mortal 2003-10-21
  • 打赏
  • 举报
回复
你把两个申明的顺序换一下

62,635

社区成员

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

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