String类

java.lang.String 类可以说是 Java 中最常被使用的一个类,它是一个很普通的类,但是又有很多特殊的地方。本文主要讲解两个部分:

① 使用不同方式创建字符串区别

② String 一个重要的特性:不可变性。

首先,以一道面试题为开始:

@Test
public void test01() {
String s1 = "hello";
String s2 = "world";

String s3 = "helloworld";
String s4 = "hello" + "world";
String s5 = new String("helloworld");
String s6 = s1 + s2;
String s7 = s1 + "world";

final String s8 = "hello";
String s9 = s8 + "world";

System.out.println("s3 == s4:" + (s3 == s4));
System.out.println("s3 == s5:" + (s3 == s5));
System.out.println("s3 == s6:" + (s3 == s6));
System.out.println("s6 == s7:" + (s6 == s7));
System.out.println("s3 == s9:" + (s3 == s9));

}

输出结果:
s3 == s4:true
s3 == s5:false
s3 == s6:false
s6 == s7:false
s3 == s9:true

使用一个或多个常量给字符串赋值时,栈中的内存地址(即变量的地址)指向的是常量池中的对象地址,并且常量池中不会存在相同内容的常量。
只要赋值等式右侧存在变量,栈中的内存地址(即变量的地址)指向的就是堆中对象的内存地址。
另外:可以调用 String 的 方法,此时,栈中的内存地址指向为常量池中对象的地址。

@Test
public void test02() {
String str1 = "helloworld";

String str2="hello";
String str3 = str2 + "world";
String str4 = str3.intern();
System.out.println("str1 == str3:" + (str1 == str3));
System.out.println("str1 == str4:" + (str1 == str4));

}

输出结果:
str1 == str3:false
str1 == str4:true
二、关于String的不可变性
如何理解 String 是一个不可变的字符序列,还是举个例子:

@Test
public void test03() {
String s1 = "helloworld";
String replace = s1.replace("o", "g");

System.out.println("s1=" + s1);
System.out.println("replace=" + replace);

String substring = s1.substring(0, 5);
System.out.println("s1=" + s1);
System.out.println("substring=" + substring);

}

输出结果:
s1=helloworld
replace=hellgwgrld
s1=helloworld
substring=hello
可见,对String变量进行任何修改都不会改变原来变量的值。

点开 String 的源码可以看到:

public final class String
implements java.io.Serializable, Comparable, CharSequence {
/** The value is used for character storage. */
private final char value[];

/** Cache the hash code for the string */
private int hash; // Default to 0

String 是一个被 final 修饰的类,这表示它是不能被继承,但是 String 的不可变性并不是指的这个,而是其中的一个成员属性:private final char value[]; 其实 String 底层是用 char 数组实现的(这点和 ArrayList 类似),这个char数组是被 final 修饰,也就是说它是不可以被修改的。所以,当对 String 进行修改时,必须重新新建一个 char 数组。这点也很容易理解,因为使用常量池的好处是,相同的对象只会存储一份,这可以大大节省内存空间,但是多个变量指向同一个常量池中的对象时,其中任何一个变量发生改变都不应该影响其他变量的值,所以只能重新去创建一个对象。

我们平时比较字符串相等时,一般都是使用 String 类中的 equals() ,下面是它的源码,可以看出,它是先去比较两个变量的地址值是否相等,然后再去判断类型是否是 String 类型,如果是 String 类型就通过遍历挨个比较每个char字符是否相同,否则返回false。

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;
}
总结:String 其实是 Java中一个普通的类,但是它有一些特殊的地方,主要需要理解的是使用不同方式创建字符串时,JVM是如何分配内存的,另外,要理解 String 的不可变性,其底层是使用一个被 final 修饰的 char 类型的数组存储数据的。

posted @ 2020-11-17 08:33  顾生  阅读(87)  评论(0编辑  收藏  举报