1. 程式人生 > >在JDK 6和JDK 7的substring()方法的區別?

在JDK 6和JDK 7的substring()方法的區別?

val 執行 println out 方法 substr tps ima pub

原文鏈接:https://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/

在JDK 6和JDK 7中substring(int beginIndex,int endIndex)的實現是不同的,下面將會做出詳細的解釋。為簡單起見,substring()方法表示的substring(int beginIndex,int endIndex)在這篇文章中的方法。

1.substring()方法

substring(int beginIndex,int endIndex)方法的返回值是,從beginIndex開始到endIndex-1結束的字符串.

String x = "abcdef";
x = x.substring(1,3);
System.out.println(x);

輸出結果:

bc

2.執行substring()的時候底層的運行機制是什麽?

你可能知道,字符串x是不可變的,當x執行subtring(1,3)方法時候,返回值指向了一個新的字符串。如下圖所示:

技術分享圖片

然而,這個圖表並不完全正確。JDK 6和JDK 7在執行substring()究竟發生了什麽呢?

3.substring()方法在JDK6中的使用。

字符串後端是char數組形式保存的。在JDK 6中,字符串包含3個字段:char value[],int offset,int count。它們用於存儲真正的字符數組、數組的第一個索引、字符串中的字符數。

當substring()方法被調用時,它將創建一個新字符串,字符串的值但仍然指向堆中的同一個數組。兩個字符串之間的差值是它們的計數和偏移值。

技術分享圖片

下面的代碼簡化了,只包含解釋這個問題的關鍵點:

//JDK 6
String(int offset, int count, char value[]) {
	this.value = value;
	this.offset = offset;
	this.count = count;
}
 
public String substring(int beginIndex, int endIndex) {
	//check boundary
	return  new String(offset + beginIndex, endIndex - beginIndex, value);
}

4.一個在JDK 6 substring()引發的問題。

如果你有一個很長的字符串,但是你只需要一小部分,每次用substring()。這會導致性能問題,因為你只需要一小部分,你就保留整個事情。JDK 6,解決的辦法是使用以下,這將使它指向一個真正的子串:

x = x.substring(x, y) + ""

5.substring()方法在JDK7中的使用。

這是在JDK 7的改進。JDK 7中的方法,substring()實際上創建在堆一個新的數組

技術分享圖片

//JDK 7
public String(char value[], int offset, int count) {
	//check boundary
	this.value = Arrays.copyOfRange(value, offset, offset + count);
}
 
public String substring(int beginIndex, int endIndex) {
	//check boundary
	int subLen = endIndex - beginIndex;
	return new String(value, beginIndex, subLen);
}

在JDK 6和JDK 7的substring()方法的區別?