码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-04-11 10:24:10      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:off   sel   没有   point   字符数组   string类   this   cal   https   

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

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

标签:off   sel   没有   point   字符数组   string类   this   cal   https   

原文地址:https://www.cnblogs.com/yrt789/p/12677666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!