日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java.lang中String类源码分析

發布時間:2025/4/17 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java.lang中String类源码分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、類
public final class String:final關鍵字說明String類不能被修改(不能被其他類繼承和重寫)

public final class Stringimplements java.io.Serializable, Comparable<String>, CharSequence

二、方法
1、subString(int beginIndex, int endIndex):截取子字符串
1) 第一層方法

public String substring(int beginIndex, int endIndex) {// beginIndex校驗不能小于0if (beginIndex < 0) {throw new StringIndexOutOfBoundsException(beginIndex);}// endIndex校驗不能>數組長度if (endIndex > value.length) {throw new StringIndexOutOfBoundsException(endIndex);}// 獲取要截取的子字符串的長度int subLen = endIndex - beginIndex;if (subLen < 0) {throw new StringIndexOutOfBoundsException(subLen);}// 判斷return ((beginIndex == 0) && (endIndex == value.length)) ? this: new String(value, beginIndex, subLen);}

2) 調用String的有參構造方法

public String(char value[], int offset, int count) {// beginIndex不能小于0if (offset < 0) {throw new StringIndexOutOfBoundsException(offset);}// count = endIndex-beginIndex <=0的情況if (count <= 0) {// count小于0,拋出異常if (count < 0) {throw new StringIndexOutOfBoundsException(count);}// count = 0時,輸出空字符串if (offset <= value.length) {this.value = "".value;return;}}// endIndex > value.length長度時拋出異常if (offset > value.length - count) {throw new StringIndexOutOfBoundsException(offset + count);}// 執行數組復制this.value = Arrays.copyOfRange(value, offset, offset+count);}

3) 調用Arrays.copyOfRange方法實現復制數組中元素到另外一個char數組中

public static char[] copyOfRange(char[] original, int from, int to) {int newLength = to - from;if (newLength < 0)throw new IllegalArgumentException(from + " > " + to);// 聲明一個char數組,用來裝載截取的子字符串char[] copy = new char[newLength];// 核心代碼,最終通過它實現將char原始數組中的元素復制到另外一個char數組中System.arraycopy(original, from, copy, 0,Math.min(original.length - from, newLength));return copy;}

未完待續~

總結

以上是生活随笔為你收集整理的java.lang中String类源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。