2.6 使用String不一定创建对象 2.7使用new String一定创建对象

2.6 使用String不一定创建对象

在执行到双引号包含字符串的语句时,如String a = "123"; JVM先会到常量池里查找,如果有的话返回常量池里的这个实例的引用,否则的话创建一个新实例并置入常量池里。所以,当我们在使用诸如String str = "abc";的格式定义对象时,总是想当然的认为,创建了String类的对象str。担心陷阱!对象可能并没有被创建!而可能是指向一个先前已经创建的对象。只是通过new()方法才能保证每次都创建一个新的对象。

2.7使用new String一定创建对象

在执行Stirng a = new String("123")的时候,首先走常量池的路线取到一个实例的引用,然后再堆上创建一个新的String实例,走以下构造函数给value属性赋值,然后把实例引用赋值给a:

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.
            int off = original.offset;
            v = Arrays.copyOfRange(originalValue, off, off+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的实例,但是value是等于常量池中的实例的value,即是说没有new 一个新的字符数组来存放"123";

github:https://github.com/ccy524946/theInterviewQuestions

来源:公司LOGO设计

猜你喜欢

转载自www.cnblogs.com/1994july/p/12676666.html