JAVA中String.intern方法(JDK1.7及以上版本)

本文介绍了JAVA中String.intern()方法的原理和行为。该方法是一个native方法,当调用时,如果字符串常量池已有相等字符串,就返回池中的引用;否则将此String对象添加到池并返回其引用。通过两个实例解释了intern方法如何影响字符串引用的指向。
摘要由CSDN通过智能技术生成

intern源码如下:

/**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * When the intern method is invoked, if the pool already contains a
     * string equal to this {@code String} object as determined by
     * the {@link #equals(Object)} method, then the string from the pool is
     * returned. Otherwise, this {@code String} object is added to the
     * pool and a reference to this {@code String} object is returned.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
   
Java ,`String.intern()` 是一个用于字符串对象的方法。它的作用是将字符串对象添加到字符串常量池,并返回常量池该字符串的引用。 具体含义如下: 1. 字符串常量池:Java 的字符串常量池是一个特殊的内存区域,用于存储字符串字面值。当创建字符串时,如果字符串常量池已经存在相同的字符串字面值,则会直接返回常量池的引用,而不会创建新的对象。 2. `String.intern()` 方法:`intern()` 方法是 `String` 类提供的一个实例方法。调用它会检查当前字符串对象在常量池是否存在。如果存在,则返回常量池的引用;如果不存在,则将当前字符串对象添加到常量池,并返回该引用。 使用 `String.intern()` 方法的主要目的是节省内存和提高性能。通过将字符串对象放入常量池,可以重复使用相同的字符串字面值,减少内存占用,并且可以更快地比较字符串的相等性。 例如: ```java String str1 = new String("Hello"); String str2 = str1.intern(); System.out.println(str1 == str2); // false System.out.println(str1.equals(str2)); // true ``` 在上面的例子,`str1` 是通过 `new String("Hello")` 创建的新字符串对象,而 `str2` 是通过 `str1.intern()` 返回的常量池的引用。虽然它们的值相等,但它们是不同的对象,所以 `str1 == str2` 返回 `false`,而 `str1.equals(str2)` 返回 `true`。 需要注意的是,`String.intern()` 方法可能会在某些情况下导致一些性能问题和潜在的内存泄漏。因此,在使用时要注意评估场景和潜在的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值