string类内存解析

String是java常用类中最重要的类,主要是它很多特殊点,网上分析的例子很多,我
也想谈下自己的看法,最经典的问题是String a=new String("abc");是如何实现创建
2个对象的?
   我们看下String的构造方法,SUN(ORACLE),JDK源码的解释:
/**
     * Initializes a newly created <code>String</code> object so that it
     * represents the same sequence of characters as the argument; in other
     * words, the newly created string is a copy of the argument string. Unless 
     * an explicit copy of <code>original</code> is needed, use of this 
     * constructor is unnecessary since Strings are immutable. 
     *
     * @param   original   a <code>String</code>.
     */
    public String(String original) {
	int size = original.count;
	char[] originalValue = original.value;
	char[] v;
  	if (originalValue.length > size) {
 	    // The array representing the String is bigger than the new
 	    // String itself.  Perhaps this constructor is being called
 	    // in order to trim the baggage, so make a copy of the array.
	    v = new char[size];
 	    System.arraycopy(originalValue, original.offset, v, 0, size);
 	} else {
 	    // The array representing the String is the same
 	    // size as the String, so no point in making a copy.
	    v = originalValue;
 	}
	this.offset = 0;
	this.count = size;
	this.value = v;
    }


也就是说String类在init的时候就已经创建了一个char数组对象(数组对象也是存放在堆内存中),我们可以用一个图来形象的表示下:

从图里我们可以看到开始new的时候需要进行2个步骤,先init再new,由于普通类init的时候不会创建对象,只有在new的时候才创建,也就只能创建一个对象,而String不一样,在初始化的时候就已经创建了一个对象,当new的时候又会再创建一个,自然是2个,而a引用new处理的...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值