欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

String类内存解析

程序员文章站 2022-06-07 17:38:12
...
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数组对象(数组对象也是存放在堆内存中),我们可以用一个图来形象的表示下:
String类内存解析
            
    
    博客分类: java基础 javaString内存解析
从图里我们可以看到开始new的时候需要进行2个步骤,先init再new,由于普通类init的时候不会创建对象,只有在new的时候才创建,也就只能创建一个对象,而String不一样,在初始化的时候就已经创建了一个对象,当new的时候又会再创建一个,自然是2个,而a引用new处理的...
  • String类内存解析
            
    
    博客分类: java基础 javaString内存解析
  • 大小: 25.5 KB