String与JVM学习笔记

目录

源码

 初始化部分

 方法

JVM

创建

常量池

+与append

面试题1:String,StringBuffer,StringBuilder区别

面试题2:String a = new String("kexin");生成了几个对象


  • 源码

  •  初始化部分

        实现了Serializable, Comparable, CharSequence三个接口,分别是序列化,compareTo,和CharSequence,第三个主要继承了一些常用方法,length,charAt, subSequence等,subSequence类似subString,效果相同,返回值类型有区别,基本不做使用

     public final class String
     implements java.io.Serializable, Comparable<String>, CharSequence {
//     存储空间,字符数组形式
    private final char value[];
//    hashcode缓存,String常用于比较,每次计算太过麻烦,这样节省时间
    private int hash; 
//    序列号(尚未理解)
    private static final long serialVersionUID = -6849794470754667710L;
  •  方法

复制 

//内部方法,将String的字符数组value整个复制到dst字符数组中,在dst数组的dstBegin位置开始拷贝
void getChars(char dst[], int dstBegin) {
        System.arraycopy(value, 0, dst, dstBegin, value.length);
    }


public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

对比

public boolean equals(Object anObject) {
//如果对象引用地址相同
        if (this == anObject) {
            return true;
        }
//这个是?存疑
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
//字符数组长度相同
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
//每个字符相同
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

比较(留待补充)

 public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

切割

 public String substring(int beginIndex, int endIndex) {
        if (beginIndex < 0) {
            throw new StringIndexOutOfBoundsException(beginIndex);
        }
        if (endIndex > value.length) {
            throw new StringIndexOutOfBoundsException(endIndex);
        }
        int subLen = endIndex - beginIndex;
        if (subLen < 0) {
            throw new StringIndexOutOfBoundsException(subLen);
        }
//生成新对象
        return ((beginIndex == 0) && (endIndex == value.length)) ? this
                : new String(value, beginIndex, subLen);
    }

 替换(留待补充)

 public String replace(char oldChar, char newChar) {
        if (oldChar != newChar) {
            int len = value.length;
            int i = -1;
            char[] val = value; /* avoid getfield opcode */

            while (++i < len) {
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];
                }
                while (i < len) {
                    char c = val[i];
//替换
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }


从以上源码也可以看出,对String对象的任何改变都不影响到原对象,相关的任何change操作都会生成新的对象

  • JVM

  • 创建

这里有个概念,叫做享元模式(Flyweight),我的理解是共享常量池中已有的元素,减少内存开支
创建方式分两种
1.String a = "a";
创建时,jvm会先判断常量池中是否已经存在"a",若存在则直接引用,若不存在则实例化该字符串再引用
最后,栈中存储了字符串常量池中"a"的引用地址
2.String b = new String("A");
先new一个字符串对象放在堆中,而堆中存储的则是指向常量池中"A"的引用地址,对于常量池引用地址的获取操作同上
最后,栈中存储了堆中的字符串对象的引用地址
所以,常量池中不可能存在两个相同的字符串,这是字符串的不可变性的体现

 

  • 常量池


常量池分两种,静态常量池与运行时常量池
编译期-静态常量池-运行前已经放置好了-常量-如String a = "1";String a1 = "1"+"2";
运行时-运行时常量池-运行时才会生成-变量-如String b = new String("1");String b1 = "1"+b;
注意:
(1):JVM对String str="abc"对象放在常量池中是在编译时做的,而String str3=str1+str2是在运行时刻才能知道的。new对象也是在运行时才做的。
(2):字面量"+"拼接是在编译期间进行的,拼接后的字符串存放在字符串池中;而字符串引用的"+"拼接运算实在运行时进行的,新创建的字符串存放在堆中。

静态常量池,class文件中的,存储了字符串,类和方法的信息等,占class的大部分内存空间
运行时常量池,jvm完成类装载操作后会将class的常量池放到方法区中,一般说常量池就是指这个在方法区中的常量池
 

JVM

intern

intern方法是一个native方法,intern方法会从字符串常量池中查询当前字符串是否存在,如果存在,就直接返回当前字符串;如果不存在就会将当前字符串放入常量池中,之后再返回。

  • +与append


String中的+在编译阶段被解释为,创建StringBuffer对象,调用append()方法,在调用toString(),最后销毁StringBuffer对象这一过程
如String A= "11"+"22"+Str1+"33"; 这一过程在编译时被解释为String A = new StringBuffer("1122").append(Str).append("33").toString();
所以当需要在循环中进行+操作时,实际上会消耗大量性能在StringBuffer的创建与销毁上,这里最好手动new一个StringBuffer来代替String

  • 面试题1:String,StringBuffer,StringBuilder区别


面试常问的问题之一
(1)可不可变,String用final修饰,静态不可变,其他两个长度可变,这也是为什么有时候用append而不用+,append是在原基础扩容,而+则是新建String
(2)是否线程安全,String不可变(可理解为常量),不会出现多个线程同时改变一个资源引起冲突的情况,所以视为安全
   StringBuffer内部用synchronized加同步锁,线程安全,StringBuffer没有,所以非线程安全
(3)执行效率,相对来说,StringBuilder > StringBuffer > String,具体情况具体分析
(4)各自特点,少量数据String灵活多变,大量数据多线程StringBuffer线程安全,大量数据单线程StringBuilder速度更快

 

  • 面试题2:String a = new String("kexin");生成了几个对象


在类加载阶段,生成了一个对象"kexin"放在堆中
在执行阶段,生成了一个对象a
所以是两个


以上掺杂部分个人理解,欢迎讨论并指正
参考资料

https://blog.csdn.net/yulungggg/article/details/81039655

https://blog.csdn.net/qq_34490018/article/details/82110578

https://www.cnblogs.com/xiaoxi/p/6036701.html

猜你喜欢

转载自blog.csdn.net/qq_36766417/article/details/107936176