前置说明:equals和==的区别
Java 语言里的 equals方法其实是交给开发者去覆写的,让开发者自己去定义满足什么条件的两个Object是equal的。参考:https://blog.youkuaiyun.com/lglglgl/article/details/104973047
Class String源码(部分)
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
/**
* String底层是使用字符数组存储的
*/
private final char value[];
/**
* 用于缓存字符串的哈希值,默认为0
*/
private int hash;
private static final long serialVersionUID = -6849794470754667710L;
private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
/**
*初始化新创建的{@code String}对象,使其表示一个空字符序列。注意,不需要这个构造函数的用法,因为字符串是不可变的。
*/
public String() {
this.value = "".value;//this.value = "".value,意思指长度为零的空字符串
}
/**
* 新创建的字符串是一份复制品
* newly created string is a copy of the argument string.
*/
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
源码注释
- String底层是使用字符数组存储的
- 所有String字符串被创建后就不可改变,因此创建后的字符串底层是共享的。
- String类里面的value包括一个
hash(int)和private final char value[],广义上只要两者任一值不同,既是不同。
测试类
package test;
public class string {
public static void main(String[] args) {
String a = "hello";
String b = "world";
final String c = "hello";
String d = "helloworld";
String e = "hello" + "world";
String f = "hello" + b;
String g = c + b;
String h = c + "world";
String i = a + b;
String j = a + b;
System.out.println(d == e);//1
System.out.println(d == f);//0
System.out.println(d == g);//0
System.out.println(d == h);//1
System.out.println(d == i);//0
System.out.println(g == h);//0
System.out.println(i == j);//0
}
}
测试类注解
| name | value | 备注 |
|---|---|---|
| args | String[0] (id=16) | |
| a | “hello” (id=19) | 内存开辟一块空间,以字符数组存储 |
| b | “world” (id=23) | 内存开辟一块空间,以字符数组存储 |
| c | “hello” (id=19) | 共享a,一个常量,代表了hello字符串。 |
| d | “helloworld” (id=24) | 变量并指向常量池中的helloworld字符串 |
| e | “helloworld” (id=24) | 变量由两个常量相连接生成的一个helloworld字符串,与d在底层储存是一致的 |
| f | “helloworld” (id=29) | 变量由一个常量和一个变量连接生成的字符串,在运行时会在堆内存中开辟新的空间保存这个字符串。 |
| g | “helloworld” (id=31) | 变量由一个常量c(即hello)和一个变量连接生成的字符串,在运行时同样会在堆内存中开辟新的空间保存这个字符串。 |
| h | “helloworld” (id=24) | 变量由一个常量c(可以认为c就是“hello”这个字符串)和另一个常量world连接生成的一个常量helloworld,与d在底层储存是一致的。 |
| i | “helloworld” (id=33) | 变量由一个变量a和另一个变量b连接生成的新的字符串,在运行时会在堆内存中开辟新的空间保存这个字符串。 |
| j | “helloworld” (id=35) | 变量由一个变量a和另一个变量b连接生成的新的字符串,在运行时会在堆内存中开辟新的空间保存这个字符串。 |
代码注意
避免频繁申请及浪费内存空间,建议使用 final对String限定,参考:
System.out.println(g == h);//0
System.out.println(d == h);//1
参考
https://blog.youkuaiyun.com/qq_21963133/article/details/79660085
本文详细解析了 Java 中 String 类的内部实现,包括其如何使用字符数组存储字符串、字符串不可变性的原理,以及 equals 和 == 的区别。通过源码分析和测试类示例,帮助读者理解字符串在 Java 中的工作机制。
457

被折叠的 条评论
为什么被折叠?



