String类是不可变类,即一个String对象被创建以后,包含在这个对象中的字符序列是不可改变的,直至这个对象被销毁。
String 有两种创建方式:
String s1="hello world";
String s2 = new String("hello world");
事实上,如果你尝试判断 s1 是否等于 s2 时,答案是不等于!
System.out.println(s1==s2); // false
当然,如果你使用 equals 去比较 s1 和 s2 是否相等时,结果是 true,这是因为 String 重写了 equals 方法【equals 源码参考附1 】。
主线还是分析 String 本身。
不变性分析
在 String 源码中 value 的定义:
/**
* 该值用于字符存储【即 value 是真正存放 String 的值的的地方】
*/
private final char value[];
注意 value 是由 final 修饰的字符数组,因此 String 的值一旦被初始化后便不能被修改。这也就回答了一开始提到的:【String类是不可变类,即一个String对象被创建以后,包含在这个对象中的字符序列是不可改变的,直至这个对象被销毁。】
但下面的情况又作何解释:
String s1="hello world";
s1 = "hello world, just kidding";
System.out.println(s1); // hello world, just kidding
说好的不可变呢,这里却被改成功了!
再看这句话:【String类是不可变类,即一个String对象被创建以后,包含在这个对象中的字符序列是不可改变的,直至这个对象被销毁。】
其中提到:包含在这个对象中的字符序列是不可改变的。也就是 value 是不可以修改的。
然后真实的情况是,value 不能被修改,而最后呈现的值却被修改了,那么就只有一种情况:s1 已经是一个新的 String 对象了。所以从严格意义上来说,我们并没有修改 s1,而是替换了 s1 。
注:关于 final 修饰的数组
在 Spring 中,用 final 修饰了 value,但是大家知道,final 关键字修饰的数组,其引用(即数组的地址)不可变,但是数组中的元素是可以修改的。那这里的 value 是否也可以单独修改呢?
答案是不可以,因为 value 的访问级别为 private,根本不可能穿透 String 对象单独修改 value 。
private final char value[];
构造器
构造器源码:【String 有很多构造器,这里仅选出几个有代表意义的】
1、无参构造器
public String() {
this.value = "".value;
}
其真实构建步骤是:
- 先通过字面量的方式声明空字符串 “”;
- 再调用其 value 赋值给当前字符串。
2、传入 String 初始值的构造器
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
结合无参构造器分析:
- 这里 JVM 会先使用常量池来管理 original 直接量,如果当前常量池中有 original 这个字符串,那么将其 value 赋值给当前对象,随后再将这个新对象保存在堆内存中(并且堆中对象的数据会指向常量池中的直接量)。如果常量池没有,则会首先在常量池中创建 original,然后再赋值,再保存新对象。
- hash,保存当前 String 对象的 hashcode 。
3、带 char value[] 的构造器
public String(char value[]) {
// 直接复制 value[],然后赋值给 value
this.value = Arrays.copyOf(value, value.length);
}
public String(char value[], int offset, int count) {
// ...省略一堆增强健壮性的代码
// 也就是个范围复制
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
String 的两种创建方式比较
参考:Java中 String类的详解 中的额外补充部分【写的很棒,为博主点赞!!!】
附录
附1:String equals 方法源码如下:
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;
}
附2:部分方法的源码分析
注:以下方法都删去了部分非主逻辑代码
1、char charAt(int index):返回指定索引处的字符
public char charAt(int index) {
// 数组通过下标取值
return value[index];
}
2、String substring(int beginIndex, int endIndex):从此字符串中截取出一部分子字符串
public String substring(int beginIndex, int endIndex) {
int subLen = endIndex - beginIndex; // 计算要复制的值的个数
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
// 仅带起始位置的 substring 方法
public String substring(int beginIndex) {
int subLen = value.length - beginIndex; // 计算要复制的值的个数
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
从源码可以知道:substring 复制的范围应该是【左闭右开】区间
3、int indexOf(String str):返回子串在此字符串首次出现的索引
public int indexOf(int ch) {
return indexOf(ch, 0); // 从第一个位置开始
}
// 主要的逻辑执行
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
return -1; // 超出最大范围
}
// MIN_SUPPLEMENTARY_CODE_POINT:Unicode 补充码位的最小值,常数 U+10000。
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// 处理正常的 ch 值下的检索
final char[] value = this.value;
// 遍历查找
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
4、String concat(String str):拼接两个字符串
public String concat(String str) {
if (str.isEmpty()) {
return this;
}
int len = value.length;
int otherLen = str.length();
// 生成一个足够容量的新的char[],内部实现依旧是 System.arraycopy
char buf[] = Arrays.copyOf(value, len + otherLen);
// 调用 System.arraycopy ,将 str 添加到 buf 指定 len 为起始位置的地方
str.getChars(buf, len);
return new String(buf, true);
}
5、public char[] toCharArray:将 string 转为 chrt数组
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
6、public static String valueOf:将传入类型转为字符串
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count); // 实现结果类似 subString
}
public static String valueOf(boolean b) {
return b ? "true" : "false"; // 注意这里的转换结果
}
public static String valueOf(int i) {
return Integer.toString(i);
}
// 数字类型的都是调用对应包装类的 toString 方法实现的
7、切割 split
【注意一些特殊字符的切割情况:Java 字符串 split 踩坑记】
public String[] split(String regex) {
return split(regex, 0);
}
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 && regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
}