String类内存解析
程序员文章站
2022-06-07 17:38:12
...
String是java常用类中最重要的类,主要是它很多特殊点,网上分析的例子很多,我
也想谈下自己的看法,最经典的问题是String a=new String("abc");是如何实现创建
2个对象的?
我们看下String的构造方法,SUN(ORACLE),JDK源码的解释:
也就是说String类在init的时候就已经创建了一个char数组对象(数组对象也是存放在堆内存中),我们可以用一个图来形象的表示下:
从图里我们可以看到开始new的时候需要进行2个步骤,先init再new,由于普通类init的时候不会创建对象,只有在new的时候才创建,也就只能创建一个对象,而String不一样,在初始化的时候就已经创建了一个对象,当new的时候又会再创建一个,自然是2个,而a引用new处理的...
也想谈下自己的看法,最经典的问题是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处理的...
上一篇: 富锦月饼价格贵不贵,它的口味又有哪些呢?
下一篇: 盖浇饭的做法你想学学吗
推荐阅读
-
实例解析iOS应用多线程开发中NSthread类的用法
-
java String 类的一些理解 关于==、equals、null
-
java解析出url请求的路径和参数键值对类(解析出url请求的路径,包括页面)
-
解析Android开发优化之:对Bitmap的内存优化详解
-
解析Android获取系统cpu信息,内存,版本,电量等信息的方法详解
-
C# 字符串string和内存流MemoryStream及比特数组byte[]之间相互转换
-
浅析C#中StringBuilder类的高效及与String的对比
-
string类的常用方法(String类提供的合法的方法)
-
h5中类jQuery选择器querySelector的使用解析
-
String类的常用方法详解