String底层是用char[ ]型数组存储还是用byte[ ]型数组存储

Java的String类在JDK1.8中使用char[]存储字符,而从JDK1.9开始改为使用byte[],这一改变主要是为了节省内存。在JDK1.9的String中,value字段是@Stable的byte[],同时引入了coder字段来标识编码,如Latin1和UTF16。
摘要由CSDN通过智能技术生成


大家学习Java基本都是以jdk1.8为基础,所以可能会有点疑惑,这里简单概述一下。

在jdk1.8之前,String底层是用char[ ]型数组存储的,直到jdk1.9改为byte[ ]型数组。这样做主要是为了节约String占用的内存。

jdk1.8:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0
    //......
}

jdk1.9:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
    /**
     * The value is used for character storage.
     *
     * @implNote This field is trusted by the VM, and is a subject to
     * constant folding if String instance is constant. Overwriting this
     * field after construction will cause problems.
     *
     * Additionally, it is marked with {@link Stable} to trust the contents
     * of the array. No other facility in JDK provides this functionality (yet).
     * {@link Stable} is safe here, because value is never null.
     */
	@Stable
	private final byte[] value;
    
	/**
	* The identifier of the encoding used to encode the bytes in
	* {@code value}. The supported values in this implementation are
	*
	* LATIN1
	* UTF16
	*
	* @implNote This field is trusted by the VM, and is a subject to
	* constant folding if String instance is constant. Overwriting this
	* field after construction will cause problems.
	*/
    private final byte coder;
    
    /** Cache the hash code for the string */
    private int hash; // Default to 0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值