java中intern的用法
时间: 2023-05-23 15:05:20 浏览: 49
A:在Java中,String类型的字符串对象有一个intern()方法,该方法可以将字符串对象加入到字符串池中,如果字符串池中已经存在该字符串,则返回字符串池中的引用,否则将该字符串加入池中并返回。
使用intern()方法可以减少内存使用量。例如:
String str1 = "Hello";
String str2 = new String("Hello");
if (str1 == str2) { // false
System.out.println("str1 == str2 is true");
}
if (str1.intern() == str2.intern()) { // true
System.out.println("str1.intern() == str2.intern() is true");
}
在上面的示例中,str1和str2所指向的字符串内容相同,但它们却不是同一个对象。通过intern()方法可以将这两个字符串对象所对应的字符串加入到字符串池中,使它们都指向池中的同一个字符串对象。这样比起使用new操作符创建新的字符串对象来说,内存使用量就会更低。
相关问题
java中intern() 方法
在Java中,字符串是不可变的,即一旦创建就不能更改其内容。Java中的intern()方法是一个本地方法,用于将字符串添加到字符串池中,并返回该字符串的引用。如果字符串池中已经存在该字符串,则返回池中该字符串的引用,否则将该字符串添加到池中,并返回新字符串的引用。
以下是使用intern()方法的示例:
```java
String str1 = "hello";
String str2 = new String("hello");
String str3 = str2.intern();
System.out.println(str1 == str2); // false
System.out.println(str1 == str3); // true
```
在上面的示例中,str1和str2是两个不同的对象,因为str2是使用new操作符创建的。然而,通过调用str2的intern()方法,我们将它添加到字符串池中,并返回池中该字符串的引用,即str3。因此,str1和str3引用的是同一个对象,因此最后一行的输出结果为true。
jdk 1.8 java.intern()
在JDK 1.8中,Java的intern()方法有一些变化。在JDK 1.7及之前的版本中,intern()方法会将字符串添加到常量池中,并返回常量池中的引用。但是在JDK 1.8中,如果常量池中已经存在该字符串,则直接返回常量池中的引用,否则将该字符串添加到常量池中,并返回常量池中的引用。
下面是一个示例,演示了在JDK 1.8中使用intern()方法的行为:
```java
String s1 = new String("hello");
String s2 = s1.intern();
String s3 = "hello";
System.out.println(s1 == s3); // false
System.out.println(s2 == s3); // true
```
在这个示例中,s1是一个新的字符串对象,它不在常量池中。调用s1.intern()方法将字符串添加到常量池中,并返回常量池中的引用。因此,s2和s3都引用常量池中的同一个字符串对象,所以s2 == s3返回true。