我已经写了代码,但请告诉我String类的intern()方法的功能,它是否尝试将池对象地址和内存地址放在同一页上?
我已经开发了以下代码:
public class MyClass
{
static String s1 = "I am unique!";
public static void main(String args[])
{
String s2 = "I am unique!";
String s3 = new String(s1).intern();// if intern method
is removed then there will be difference
// String s3= new String("I am unique!").intern();
System.out.println("s1 hashcode -->"+s1.hashCode());
System.out.println("s3 hashcode -->"+s3.hashCode());
System.out.println("s2 hashcode -->"+s2.hashCode());
System.out.println(s1 == s2);
System.out.println("s1.equals(s2) -->"+s1.equals(s2));
/* System.out.println("s1.equals(s3) -->"+s1.equals(s3));
System.out.println(s1 == s3);
System.out.println(s3 == s1);
System.out.println("s3-->"+s3.hashCode());*/
// System.out.println(s3.equals(s1));
}
}现在,上面的intern()方法的作用是什么?
由于这些方法都是相同的,所以请解释一下intern()方法的作用。
提前谢谢。
发布于 2012-05-01 15:36:08
由于operator==检查的是身份,而不是相等性,因此System.out.println(s1 == s3); (被注释掉)只有在s1和s3是完全相同的对象时才会生成s3。
intern()方法确保了这一点,因为两个字符串- s1和s3彼此相等,通过分配它们的intern()值,您可以确保它们实际上是相同的对象,而不是两个不同但相等的对象。
正如javadocs所说:
对于任意两个字符串s和t,s.intern() == t.intern()为真的充要条件是s.equals(t)为真。
附注:您不会在s1上调用intern(),因为它是一个String literal,因此已经是规范的。
但是,它对s1 == s2没有影响,因为它们都是字符串文字,并且intern()都不会在这两个字符串上调用。
发布于 2012-05-01 15:36:11
此方法返回string对象的规范表示形式。由此得出,对于任意两个字符串s和t,当且仅当s.equals(t)为真时,s.intern() == t.intern()为真。
返回string对象的规范表示形式。
参考http://www.tutorialspoint.com/java/java_string_intern.htm
如果调用此String对象的intern方法,
str = str.intern();JVM将检查JVM维护的字符串池是否包含任何与str对象具有相同值的String对象,并且equals方法返回true。
如果JVM找到这样的对象,则JVM将返回对字符串池中存在的该对象的引用。
如果字符串池中不存在与当前对象相等的对象,则JVM将该字符串添加到字符串池中,并将其引用返回给调用对象。
JVM将对象添加到字符串池中,以便下次任何字符串对象调用intern方法时,如果这两个字符串的值相等,就可以进行空间优化。
您可以使用equals和==运算符检查intern方法的工作情况。
参考:http://java-antony.blogspot.in/2007/07/string-and-its-intern-method.html
发布于 2012-05-01 15:37:28
从String.intern() Javadoc
一个字符串池,最初为空,由类String私有维护。
当调用intern方法时,如果池中已经包含了一个字符串,该字符串与equals( object )方法所确定的字符串对象相同,那么将返回池中的字符串。否则,此String对象将添加到池中,并返回对此String对象的引用。
由此得出,对于任意两个字符串s和t,当且仅当s.equals(t)为真时,s.intern() == t.intern()为真。
所有的文字字符串和字符串值的常量表达式都是内嵌的。字符串文字在Java规范的3.10.5小节中定义。
返回:与此字符串具有相同内容的字符串,但保证来自唯一字符串池。
您是否有Javadoc没有涵盖的更具体的疑问?
https://stackoverflow.com/questions/10394850
复制相似问题