变态Java系列 String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhu7727926/article/details/81386276

1.String的常见定义

先看String的源码

public final class String{

 private final char value[];

}

可以看出不论是String本身还是实现都是final的,表明String不仅不能被复写,连它里面存数组的域都是final的,意思你一旦初始化它你就没法改它了,这点很重要。

2.String的实现方式

常见:

        String a = new String("abc");
        String a1 = "abc";
        String a2 ="a"+"b";

这里涉及到常量池和堆,具体可以参考

String的实现方式

https://blog.csdn.net/gyaod/article/details/52761184

看上面的文章我门看下面这道题:

public class Test {

    public static void main(String[] args) {
        String a = new String("abc");
        String a1 = "abc";
        System.out.println(a.hashCode());
        System.out.println(a1.hashCode());
        System.out.println(a.hashCode() == a1.hashCode());
        System.out.println(a == a1);

        Integer b = Integer.valueOf(123);
        Integer b1 = 123;
        System.out.println(b == b1);

        Integer c = Integer.valueOf(789);
        Integer c1 = 789;
        System.out.println(c == c1);

    }
}

输出:true
           false
           true
           false

       对象1 == 对象2  其实比较的不是hashcode 比较的是指针地址(指针地址 不一定就是hashcode 如果没有重写过hashcode  那么hashcode就是指针地址)

integer 有常量池的

这里需要注意 String a2 ="a"+"b";

String a = "hello2";

final String b = "hello";

String c = "hello";

 

System.out.println(a==(b+2));

System.out.println(a==(c+2));

true

false

a==(b+2) 用final声明的变量为常量,也就是说a==(b+2)和a==("hello"+2)效果是一样的
a==(c+2) c+2 会返回 new String"hello2")而不是在常量池里寻找出来的

通过“”+“”拼接方式来实现其实new String 别会使用

使用常量池中的String a

字符串拼接原理:运行时, 两个字符串str1, str2的拼接首先会调用 String.valueOf(obj),这个Obj为str1,而String.valueOf(Obj)中的实现是return obj == null ? “null” : obj.toString(), 然后产生StringBuilder, 调用的StringBuilder(str1)构造方法, 把StringBuilder初始化,长度为str1.length()+16,并且调用append(str1)! 接下来调用StringBuilder.append(str2), 把第二个字符串拼接进去, 然后调用StringBuilder.toString返回结果!

猜你喜欢

转载自blog.csdn.net/zhu7727926/article/details/81386276