日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java.lang中String类源码分析

發布時間:2025/4/17 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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类源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。

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