
🍁 作者:知識淺談,CSDN部落格專家,阿裡雲簽約部落客,InfoQ簽約部落客,華為雲雲享專家,51CTO明日之星
📌 擅長領域:全棧工程師、爬蟲、ACM算法
💒 公衆号:知識淺談
String源碼分析(三)總結
🤞這次都給他拿下🤞
正菜來了⛳⛳⛳
🎈String類中的相關函數解析
🍮getChars(char dst[], int dstBegin)
含義:這個函數的主要作用就是吧String中的數組指派到dst數組中,其内部調用System.arraycopy這個函數進行實作,關于這幾個參數的不同意思。
- value: 源數組
- 0:源數組開始的位置。
- dst:目标數組,即要複制到目标數組中。
- dstBegin:目标數組開始的位置。
- value.length:要拷貝的字元串的長度。
void getChars(char dst[], int dstBegin) {
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
🍮void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
含義:這個函數的主要作用和上邊的函數差不多,主要是就是這個指定了源數組開始的位置和結束的位置,并且指定目标數組和目标數組開始的位置。
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
🍮void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin)
含義:這個函數的意思和上邊的差不多,這個就是把String底層的指定開始和結束位置的字元拷貝到指定開始位置的目标位元組數組中。
public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
Objects.requireNonNull(dst);
int j = dstBegin;
int n = srcEnd;
int i = srcBegin;
char[] val = value; /* avoid getfield opcode */
while (i < n) {
dst[j++] = (byte)val[i++];
}
}
🍮byte[] getBytes(String charsetName)
含義:使用命名字元集将此字元串編碼為位元組序列,并将結果存儲到新的位元組數組中。未指定此字元串無法在給定字元集中編碼時此方法的行為。當需要對編碼過程進行更多控制時,應使用 java.nio.charset.CharsetEncoder 類。
通俗解釋:這個函數的意思就是把String字元串按照指定的編碼方式進行編碼,并且傳回一個位元組數組。
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null) throw new NullPointerException();
return StringCoding.encode(charsetName, value, 0, value.length);
}
上邊采用到了兩個非String中的方法,我們也來分析一下。
🍮byte[] encode(Charset cs, char[] ca, int off, int len)
含義:這個函數的意思是把String字元串按照指定的charset指定的格式進行編碼為一個位元組數組,并傳回,這個和上邊的函數比較相似,會采用StringCoding.encode這個函數進行編碼。
🍮byte[] encode(char[] ca, int off, int len)
🍮boolean equals(Object anObject)
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;
}