一, java 内部 String 类的实现:
- java 8:
- public final class String
- implements java.io.Serializable, Comparable<String>, CharSequence {
- /** The value is used for character storage. */
- private final char value[];
- }
java 9 及之后:(使用 coder 标识了编码)
- public final class String
- implements java.io.Serializable, Comparable<String>, CharSequence {
- /** The value is used for character storage. */
- private final byte[] value;
- /** The identifier of the encoding used to encode the bytes in
- {@code value}. */
- private final byte coder;
- }
二, 为何要将 String 定义为 final 不可变?
因为在程序编写的过程中, 会大量地用到 String 常量, 如果每次声明一个 String 引用都要新建一个 String 对象, 那么会造成空间的极大浪费. 于是, 在 java 的堆中开辟了一块存储空间 String pool, 用于存储 String 常量对象. 当有多个 String 引用指向同样的 String 字符串时, 实际上是指向的是同一个 Sting pool 中的对象, 而不需要额外的创建对象.
- public class Test{
- public static void main(String [] args){
- String a="abc";
- String b="abc";// 对象保存在 string pool 中
- String c=new String("abc");// 以 new 创建的对象保存在堆中
- System.out.println("a==b:"+(a==b));
- System.out.println("a==c:"+(a==c));
- }
- }
- View Code
三, String 不可变的其他好处
1, 以 String 作为 HashMap 的 key,String 的不可变保证了 hash 值的不可变.
2,String 作为网络连接的参数, 它的不可变性提供了安全性.
3,String 不可变, 所以线程安全.
来源: http://www.bubuko.com/infodetail-2996716.html