为什么String设置成不可变

答案就是为了安全。

那么string的底层原理是什么样的?下面是源码

public final class String  

implements java.io.Serializable, Comparable<String>, CharSequence{  

/** The value is used for character storage. */  

private final char value[];  

/** The offset is the first index of the storage that is used. */  

private final int offset;  

/** The count is the number of characters in the String. */  

private final int count;  

/** Cache the hash code for the string */  

private int hash; // Default to 0

很容易就看出来String就是由char类型的数组封装的,内部的成员变量都是private的,也没有提供set方法来修改这些值。

在String外部无法修改String,因为自己的变量是final修饰的,所以在String内部也不能改变。所以认为String对象是不可变的

但是用反射可以改变String对象,但是一般貌似不会这么做。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值