# 类声明

final 修饰符决定String是一个常量,是不可继承并且不可变的。String同时实现了 SerializableComparableCharSequence 三个接口。

  1. public final class String
  2. implements java.io.Serializable, Comparable<String>, CharSequence

# 属性字段

  1. // 0代表LATIN1编码,1代表UTF16编码,navite注解表示该值可能来自实现JVM的C/C++代码
  2. @Native static final byte LATIN1 = 0;
  3. @Native static final byte UTF16 = 1;
  4. // 字符串的值,核心属性,Stable和final修饰符保证稳定不可变(但是可以通过反射修改)。
  5. // 在jdk8之前使用char[]存储字符串的值
  6. @Stable
  7. private final byte[] value;
  8. // 字节编码标识符,值为LATIN1或UTF16
  9. // 当全部字符在ASCII编码范围内,coder = LATIN1
  10. // 当全部字符不能使用ASCII编码,coder = UTF16
  11. private final byte coder;
  12. // 字符串hash值,默认为0
  13. private int hash;
  14. // 序列化和反序列化使用
  15. private static final long serialVersionUID = -6849794470754667710L;
  16. // 压缩标识符,默认为ture(开启)
  17. // COMPACT_STRINGS = false表示使用UTF16编码
  18. static final boolean COMPACT_STRINGS;
  19. static {COMPACT_STRINGS = true;}
  20. // 只有serialPersistentFields中的字符字段会被序列化,优先级高于transient,默认为空
  21. private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];

# 构造方法

| package 方法

* char[]

  1. String(char[] value, int off, int len, Void sig) {
  2. // 如果数组长度为0,初始化为空字符串
  3. if (len == 0) {
  4. this.value = "".value;
  5. this.coder = "".coder;
  6. return;
  7. }
  8. // LATIN1:每个byte表示对应char的8个低位,每个char对应一个byte
  9. // UTF16:每个char对应两个byte
  10. // 是否开启压缩
  11. if (COMPACT_STRINGS) {
  12. byte[] val = StringUTF16.compress(value, off, len);
  13. if (val != null) {
  14. this.value = val;
  15. this.coder = LATIN1;
  16. return;
  17. }
  18. }
  19. this.coder = UTF16;
  20. this.value = StringUTF16.toBytes(value, off, len);
  21. }

* AbstractStringBuilder

  1. String(AbstractStringBuilder asb, Void sig) {
  2. // get value
  3. byte[] val = asb.getValue();
  4. // get length
  5. int length = asb.length();
  6. // 判断asb中是否开启压缩
  7. if (asb.isLatin1()) {
  8. this.coder = LATIN1;
  9. // 复制asb中的值
  10. // Arrays.copyOfRange()底层是通过arraycopy()实现
  11. this.value = Arrays.copyOfRange(val, 0, length);
  12. } else {
  13. // 判断本类是否开启压缩
  14. if (COMPACT_STRINGS) {
  15. byte[] buf = StringUTF16.compress(val, 0, length);
  16. if (buf != null) {
  17. this.coder = LATIN1;
  18. this.value = buf;
  19. return;
  20. }
  21. }
  22. this.coder = UTF16;
  23. this.value = Arrays.copyOfRange(val, 0, length << 1);
  24. }
  25. }

* byte[]

  1. String(byte[] value, byte coder) {
  2. // 直接给value和coder赋值
  3. this.value = value;
  4. this.coder = coder;
  5. }

| public 方法

* String

  1. // 空参数
  2. public String() {
  3. this.value = "".value;
  4. this.coder = "".coder;
  5. }
  6. // 创建一个参数字符串的副本字符串
  7. @HotSpotIntrinsicCandidate
  8. public String(String original) {
  9. this.value = original.value;
  10. this.coder = original.coder;
  11. this.hash = original.hash;
  12. }
  • 由于字符串不可变,所以不推荐使用空参数的构造方法。同样,除非需要 original 的显式副本,否则不要通过复制来新建字符串。

* char[]

调用 package 方法将 char[] 转换为字符串,第二个方法检查了数组是否越界。

char[] 再进行修改不会影响到新创建的字符串

  1. // package method:
  2. // String(char[] value, int off, int len, Void sig) {...}
  3. public String(char value[]) {
  4. this(value, 0, value.length, null);
  5. }
  6. public String(char value[], int offset, int count) {
  7. this(value, offset, count, rangeCheck(value, offset, count));
  8. }
  9. private static Void rangeCheck(char[] value, int offset, int count) {
  10. checkBoundsOffCount(offset, count, value.length);
  11. return null;
  12. }

* int[] codePoints

  • 代码点是一个整数,代表是 Unicode 字符集里的位置。Unicode目前的代码点范围是 0x0000-0x10FFFF。目前 Unicode11.0 只有 137374 个字符,还有将近 100 万个空余地址用于添加新字符,每年 Unicode 的字符集都会增加新字符。
  • 如果超出了代码点的有效值范围,会抛出java.lang.IllegalArgumentException,修改代码点数组不会影响创建的新字符串。 ```java /**
    • codePoints: 代码点源数组
    • offset: 子数组的第一个代码点索引
    • count: 子数组的长度 */

public String(int[] codePoints, int offset, int count) { checkBoundsOffCount(offset, count, codePoints.length); if (count == 0) { this.value = “”.value; this.coder = “”.coder; return; } if (COMPACT_STRINGS) { byte[] val = StringLatin1.toBytes(codePoints, offset, count); if (val != null) { this.coder = LATIN1; this.value = val; return; } } this.coder = UTF16; this.value = StringUTF16.toBytes(codePoints, offset, count); }

  1. <a name="VZxGQ"></a>
  2. ### * bytes[]
  3. 一共有 6 个使用`bytes[]`的构造方法,本质上都是使用`StringCoding.decode()`。
  4. ```java
  5. /**
  6. * bytes[]: 字节数组
  7. * offset: 开始解码的第一个字节索引
  8. * length: 解码字节个数
  9. * charsetName or charset: 支持的字符集名称,默认使用默认字符集
  10. */
  11. public String(byte bytes[], int offset, int length, String charsetName)
  12. throws UnsupportedEncodingException {
  13. if (charsetName == null)
  14. throw new NullPointerException("charsetName");
  15. checkBoundsOffCount(offset, length, bytes.length);
  16. StringCoding.Result ret =
  17. StringCoding.decode(charsetName, bytes, offset, length);
  18. this.value = ret.value;
  19. this.coder = ret.coder;
  20. }
  21. // 判断是否越界
  22. static void checkBoundsOffCount(int offset, int count, int length) {
  23. if (offset < 0 || count < 0 || offset > length - count) {
  24. throw new StringIndexOutOfBoundsException(
  25. "offset " + offset + ", count " + count + ", length " + length);
  26. }
  27. }
  28. public String(byte bytes[], int offset, int length, Charset charset)
  29. public String(byte bytes[], String charsetName)
  30. public String(byte bytes[], Charset charset)
  31. public String(byte bytes[], int offset, int length)
  32. public String(byte[] bytes)

* StringBuffer & StringBuilder

  1. public String(StringBuffer buffer) {
  2. this(buffer.toString());
  3. }
  4. // 每次调用toString方法都会更新toStringCache的值,等价于缓存了最后一次的修改值
  5. private transient String toStringCache;
  1. // package method:
  2. // String(AbstractStringBuilder asb, Void sig) {...}
  3. public String(StringBuilder builder) {
  4. this(builder, null);
  5. }

# 其他方法

| charSequence 接口方法

* 1 length()

根据字符串是否压缩来计算字符串的长度。

  1. public int length() {
  2. // 右移操作
  3. return value.length >> coder();
  4. }
  5. // 判断是否压缩
  6. byte coder() {
  7. // 压缩,则返回0,长度不变
  8. // 不压缩返回1,因为UTF16中一个字符2个byte,所以长度要减半
  9. return COMPACT_STRINGS ? coder : UTF16;
  10. }

* 2 charAt()

根据索引获取相对应字符。

  1. public char charAt(int index) {
  2. // 根据编码标识符使用不同的方法
  3. if (isLatin1()) {
  4. return StringLatin1.charAt(value, index);
  5. } else {
  6. return StringUTF16.charAt(value, index);
  7. }
  8. }
  9. // 判断编码标识符
  10. private boolean isLatin1() {
  11. return COMPACT_STRINGS && coder == LATIN1;
  12. }

* 3 isEmpty()

判断字符串是否为空。

  1. public boolean isEmpty() {
  2. // 通过长度判断
  3. return value.length == 0;
  4. }

| 比较方法

* 1 compareTo()

实现 Comparable 接口的 compareTo()。

  1. public int compareTo(String anotherString) {
  2. byte v1[] = value;
  3. byte v2[] = anotherString.value;
  4. // 编码表示相同时
  5. if (coder() == anotherString.coder()) {
  6. return isLatin1() ? StringLatin1.compareTo(v1, v2)
  7. : StringUTF16.compareTo(v1, v2);
  8. }
  9. // 编码标识符不同时
  10. return isLatin1() ? StringLatin1.compareToUTF16(v1, v2)
  11. : StringUTF16.compareToLatin1(v1, v2);
  12. }

* 2 equals()

  1. public boolean equals(Object anObject) {
  2. // 如果两个比较对象,直接返回true
  3. if (this == anObject) {
  4. return true;
  5. }
  6. // 先判断是否都是String
  7. if (anObject instanceof String) {
  8. String aString = (String) anObject;
  9. // 要求编码方式也相同
  10. if (coder() == aString.coder()) {
  11. return isLatin1() ? StringLatin1.equals(value, aString.value)
  12. : StringUTF16.equals(value, aString.value);
  13. }
  14. }
  15. return false;
  16. }
  17. // StringLatin1.equals()
  18. @HotSpotIntrinsicCandidate
  19. public static boolean equals(byte[] value, byte[] other) {
  20. if (value.length == other.length) {
  21. for (int i = 0; i < value.length; i++) {
  22. if (value[i] != other[i]) {
  23. return false;
  24. }
  25. }
  26. return true;
  27. }
  28. return false;
  29. }
  30. // StringUTF16.equals()
  31. @HotSpotIntrinsicCandidate
  32. public static boolean equals(byte[] value, byte[] other) {
  33. if (value.length == other.length) {
  34. int len = value.length >> 1;
  35. for (int i = 0; i < len; i++) {
  36. if (getChar(value, i) != getChar(other, i)) {
  37. return false;
  38. }
  39. }
  40. return true;
  41. }
  42. return false;
  43. }

* 3 hashcode()

计算公式:s[0] 31^(n-1) + s[1] 31^(n-2) + … + s[n-1],s[i] 是字符串中的第 i 个字符,n 是字符串的长度。

选择数字 31 的原因:31是一个奇质数,如果选择一个偶数会在乘法运算中产生溢出,导致数值信息丢失,因为乘二相当于移位运算。选择质数的优势并不是特别的明显,但这是一个传统。同时,数字 31 有一个很好的特性,即乘法运算可以被移位和减法运算取代,来获取更好的性能:31 * i == (i << 5) - i,现代的 Java 虚拟机可以自动的完成这个优化。

  1. public int hashCode() {
  2. int h = hash;
  3. if (h == 0 && value.length > 0) {
  4. hash = h = isLatin1() ? StringLatin1.hashCode(value)
  5. : StringUTF16.hashCode(value);
  6. }
  7. return h;
  8. }
  9. // StringLatin1.hashCode()
  10. public static int hashCode(byte[] value) {
  11. int h = 0;
  12. for (byte v : value) {
  13. h = 31 * h + (v & 0xff);
  14. }
  15. return h;
  16. }
  17. // StringUTF16.hashCode()
  18. public static int hashCode(byte[] value) {
  19. int h = 0;
  20. int length = value.length >> 1;
  21. for (int i = 0; i < length; i++) {
  22. h = 31 * h + getChar(value, i);
  23. }
  24. return h;
  25. }

# String 拼接

| Java8

在 Java8 及之前的 JDK 版本中,”+” 是通过创建StringBuilder对象并调用 append() 实现。拼接完成之后调用toString()得到String对象。

  1. String str1 = "he";
  2. String str2 = "llo";
  3. String str3 = "world";
  4. String str4 = str1 + str2 + str3;

上面代码对应的字节码如下:
image.png
Java8 在 for 循环中拼接字符串时,每拼接一次就会创建一个新的StringBuilder对象。为了避免频繁创建新对象,可以在循环开始前创建StringBuilder对象用于在循环当中拼接字符串:

  1. public static String getString1(String[] strArray){
  2. String result = "";
  3. for(int i = 0; i < strArray.length; i++)
  4. result += strArray[i];
  5. return result;
  6. }
  7. public static String getString2(String[] strArray){
  8. // 在循环开始前创建StringBuilder
  9. StringBuilder result = new StringBuilder();
  10. for(int i = 0; i < strArray.length; i++)
  11. result.append(strArray[i]);
  12. return result.toString();
  13. }

| Java 9

Java9 及之后 的 JDK 版本中,JVM 使用动态调用实现字符串之间的拼接。
image.png

| 变量和常量拼接

对于编译期可以确定值的字符串常量,JVM 会将其存入字符串常量池。并且,字符串常量拼接得到的字符串常量在编译阶段也会被存放到字符串常量池(例如str3),这得益于编译器进行的常量折叠。

常量折叠:把常量表达式的值求出来作为常量嵌在最终生成的代码中,这是 Javac 编译器对源代码做出的极少量优化措施之一。 编译器无法对引用值进行优化,因为这些值在程序编译期间无法确定。

只有编译器在程序编译期可以确定值的常量才会发生常量折叠:

  • 基本数据类型及字符串常量;
  • final修饰的基本数据类型和字符串变量;
  • 字符串通过“+”拼接得到的字符串、基本数据类型之间的算术运算、基本数据类型的位运算; ```java String str1 = “str”; String str2 = “ing”;

String str3 = “str” + “ing”; // 常量池中的对象 String str4 = str1 + str2; // 堆上的新对象 String str5 = “string”; // 常量池中的对象

System.out.println(str3 == str4); // false System.out.println(str4 == str5); // false System.out.println(str3 == str5); // true

  1. 例如上面的代码,`str3``str4`的内存地址并不相同,因为在字符串拼接时没有进行优化。如果将`str1``str2`使用 final 修饰符修饰,那么编译器会自动进行常量折叠,`str3``str4`在内存中的地址相同。
  2. ```java
  3. final String str1 = "str";
  4. final String str2 = "ing";
  5. String str3 = "str" + "ing"; // 常量池中的对象
  6. String str4 = str1 + str2; // 常量池中的对象
  7. System.out.println(str3 == str4); // true

# 参考

  1. 水木今山的博客
  2. String hashCode 方法为什么选择数字31作为乘子
  3. OpenJDK源码阅读解析:Java11的String类源码分析详解
  4. JavaGuide-String