本系列是Java详解,专栏地址:Java源码分析
String 官方文档:String (Java Platform SE 8 )
String .java源码共3348行,下载地址见我的文章:Java源码下载和阅读(JDK1.8/Java 11)
文件地址:openjdk-jdk11u-jdk-11.0.6-3/src/java.base/share/classes/java/lang
想看String源码的主要原因是String是经常被问到的一个知识点,里面有很多实现有借鉴意义。
注释
看源码的第一步是看注释。
1.String是常量,创建后不可更改。String buffer支持可变的String。
2.如果给构造函数传递null,那么会抛出异常NullPointerException。
3.String是UTF-16格式的字符串。
4.index,索引指的是char的code unit。
5.
6.
类的继承
实现了接口:Serializable和CharSequence
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
数据的存储
使用byte数组存储数据,final关键字表示是不可变的,String在创建后就不可修改。
import jdk.internal.vm.annotation.Stable;
@Stable
private final byte[] value;
根据注释:如果String示例是常量,那么会发生常量折叠constant folding。
注意,这里有个注解@Stable。
如果存在注解@Stable,HotSpot虚拟机可以做优化,如constant folding。处理final fields就像处理static final fields。
该注解仅在boot loader加载类的时候起作用,其他时候不起作用。
因为使用byte数组来存储数据,所以需要指定字符串的编码,支持UTF-16和LATIN1。
/**
* The identifier of the encoding used to encode the bytes in
* {@code value}. The supported values in this implementation are
* LATIN1
* UTF16
*/
private final byte coder;
@Native static final byte LATIN1 = 0;
@Native static final byte UTF16 = 1;
构造函数
空的构造函数还是挺新奇的。支持从String,char [],byte [],int [],StringBuffer,StringBuilder进行构造。
其中int []是Unicode code point。
byte []可以指定编码,包括UTF_8,ISO_8859_1,US_ASCII.
public String() {
this.value = "".value;
this.coder = "".coder;
}
@HotSpotIntrinsicCandidate
public String(String original) {
this.value = original.value;
this.coder = original.coder;
this.hash = original.hash;
}
public String(char value[]) {
this(value, 0, value.length, null);
}
public String(char value[], int offset, int count) {
this(value, offset, count, rangeCheck(value, offset, count));
}
public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null)
throw new NullPointerException(
Java String源码解析:构造、存储与关键函数

本文详细分析了Java 11中String类的源码,涵盖构造函数、数据存储(使用byte数组,final修饰保证不可变性)、charAt函数、equals函数、hashCode函数、indexOf函数及intern函数。String是不可变对象,构造时若传入可变对象,会创建新副本。intern函数用于字符串常量池管理,避免重复对象,提高内存效率。
最低0.47元/天 解锁文章
1279

被折叠的 条评论
为什么被折叠?



