我对实习生功能有点困惑.我有以下代码:
public class InternTest{
public static void main(String args[]){
String s1 = "ANEK";
String s2 = new String("ANEK");
String s3 = s2.intern();
System.out.println(s3 == s1); // True
String s11 = "ANEK".concat("SINGH");
String s22 = s11.intern();
System.out.println(s11 == s22); // True
String s4 = "nat".concat("ive");
String s5 = s4.intern();
System.out.println(s4 == s5); // True
String s33 = "ma".concat("in");
String s44 = s33.intern();
System.out.println(s33 == s44); // false
String s331 = "ja".concat("va");
String s441 = s331.intern();
System.out.println(s331 == s441); // false
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是关于输出.在第三种情况下,它给了我真实,但在第四和第五种情况下,它给了我错误.我能知道这些输出背后的原因是什么吗?我无法得出这样的结论:它为java保留字或关键字提供了错误,因为当我尝试使用en时它给出了真实但是通过te它给了我错误.谁能告诉我为什么?
Eug*_*ene 13
你得到你输出的输出,因为java和main字符串已经在池中了 - 当你启动应用程序时,有很多其他类被加载,其中一些已经实现了这些字符串(在你的代码到达之前)
我也期待native- 但我猜不是,这意味着没有其他人实习.
这引起了一些注意(我没想到),所以我想我会稍微扩展一下.假设你这样做:
String left = new String(new char[] { 'h', 'e', 'y' });
String right = left.intern();
System.out.println(left == right);
Run Code Online (Sandbox Code Playgroud)
这将打印,true因为"嘿"之前不在字符串池中并且由我们添加left.intern().另一方面:
String left = new String(new char[] { 'j', 'a', 'v', 'a' });
String right = left.intern();
System.out.println(left == right);
Run Code Online (Sandbox Code Playgroud)
打印,false因为当我们调用时,"java" 已经在池中left.intern.
让我们看看文档intern():
如果池已经包含一个等于此String对象的字符串(由equals(Object)方法确定),则返回池中的字符串.否则,将此String对象添加到池中,并返回对此String对象的引用.
这意味着,如果已经有一个与池中的给定值的字符串是 老被返回的字符串,否则返回的实际字符串.由于前三个字符串不是池中,实际的琴弦- s2,s11并s4返回,被添加到池后,所以这是相同的.不知何故,"main"和"java"已经在池中,intern()并且返回该字符串而不是s33或s331(假设s331.intern()为最后一次调用).
试试这个:
String tmp = "ANEKSINGH"; // so this is in the pool
String s11 = "ANEK".concat("SINGH");
String s22 = s11.intern();
System.out.println(s11 == s22); // FALSE now
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |