关于String全面解析

1.String 为什么要设计成不可变的?

本文参考jdk1.6

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. 

string class对象代表字符串,所有的文字在程序中都是作为类的实例存在的。string是常量,初始化后不能修改,stringBuffer支持修改,string不可改变所以支持共享。

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence,
               Constable, ConstantDesc {
	//The value is used for character storage.
	//方便对象的序列号
	private final byte[] value;
	private final byte coder;
	//hashcode 运算得到hashcode
	private int hash; // Default to 0

}

final 修饰value引用不可改变
Serializable 支持序列化
Comparable 可比较的
CharSequence字符序列接口
Constable 表示常量类型

总结:string是不可变得,因此可能被共享,而且在开发中使用频繁,所以能保证线程的安全。在内存方面,string的内容是放到堆内存的常量池中,即便创建多个相同内容的对象,都指向同一个常量池内的内容。提高效率。

2.new String(“hello”) 产生几个对象

1.如果常量池内没有hello,会产生两个对象,一个是堆内string对象,一个常量池的对象。
2.如果常量池有hello内容,只会创建一个string对象就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值