String str = new String("abc")创建了几个对象?结合源码解析

String str = new String("abc")创建了几个对象?结合源码解析

  首先,我们看一下jdk源码: 

 1 /**
 2      * Initializes a newly created {@code String} object so that it represents
 3      * the same sequence of characters as the argument; in other words, the
 4      * newly created string is a copy of the argument string. Unless an
 5      * explicit copy of {@code original} is needed, use of this constructor is
 6      * unnecessary since Strings are immutable.
 7      *
 8      * @param  original
 9      *         A {@code String}
10      */
11     public String(String original) {
12         this.value = original.value;
13         this.hash = original.hash;
14     }

  大家都知道String本身就是个引用类型,我们可以将String str = new String("adc")分为四部分来看,String str 第一部分变量名,=为第二部分给str赋值使用的,new String()为第三部分创建对象,"abc"为第三部分对象内容,然而第一部分和第二部分并没有创建对象。第三部分new String()肯定是创建了对象的。那么另一个对象时从何来的呢?从上面的源码中我们会看到一个带参的String的构造器;如果方法区的常量池里面没有所传的参数对象,这个参数会在方法区的常量池里面创建一个,加上我们new出来的,会有两个对象;但是如果在方法区里面有该参数,那么就会直接获取,因此jvm只会在堆里面创建对象本身,栈里面引用地址,这个时候就只有一个对象存在。所以,至于有多少个对象被创建,这个主要看之前是不是String original参数传入,要是情况而定。

  如有错误请多多指出。

posted @ 2018-01-09 16:37  houstao  阅读(2008)  评论(0编辑  收藏  举报