Java源码详解四:String源码分析--openjdk java 11源码

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


本系列是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.

类的继承

实现了接口:SerializableCharSequence

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
如果存在注解@StableHotSpot虚拟机可以做优化,如constant folding。处理final fields就像处理static final fields
该注解仅在boot loader加载类的时候起作用,其他时候不起作用。


因为使用byte数组来存储数据,所以需要指定字符串的编码,支持UTF-16LATIN1

    /**
     * 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;

构造函数

空的构造函数还是挺新奇的。支持从Stringchar []byte []int []StringBufferStringBuilder进行构造。
其中int []Unicode code point
byte []可以指定编码,包括UTF_8ISO_8859_1US_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(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值