java String部分源碼解析

String類型的成員變量

/** String的屬性值 */  private final char value[];/** The offset is the first index of the storage that is used. *//**數組被使用的開始位置**/private final int offset;/** The count is the number of characters in the String. *//**String中元素的個數**/private final int count;/** Cache the hash code for the string *//**String類型的hash值**/private int hash; // Default to 0/** use serialVersionUID from JDK 1.0.2 for interoperability */private static final long serialVersionUID = -6849794470754667710L;

?  有上面的成員變量可以知道String類的值是final類型的,不能被改變的,所以只要一個值改變就會生成一個新的String類型對象,存儲String數據也不一定從數組的第0個元素開始的,而是從offset所指的元素開始。

如下面的代碼是生成了一個新的對象,最后的到的是一個新的值為“bbaa”的新的String的值。

     String a = new String("bb");String b = new String("aa");String c =  a + b;    

?

  也可以說String類型的對象是長度不可變的,String拼接字符串每次都要生成一個新的對象,所以拼接字符串的效率肯定沒有可變長度的StringBuffer和StringBuilder快。

?

然而下面這種情況卻是很快的拼接兩個字符串的:

    String a = "aa" + "bb";

  原因是:java對它字符串拼接進行了小小的優化,他是直接把“aa”和“bb”直接拼接成了“aabb”,然后把值賦給了a,只需生成一次String對象,比上面那種方式減少了2次生成String,效率明顯要高很多。

?


?

下面我們來看看String的幾個常見的構造方法

?

1、無參數的構造方法:

public String() {this.offset = 0;this.count = 0;this.value = new char[0];}

?

?

2、傳入一個Sring類型對象的構造方法

public String(String original) {int size = original.count;char[] originalValue = original.value;char[] v;if (originalValue.length > size) {// The array representing the String is bigger than the new// String itself.  Perhaps this constructor is being called// in order to trim the baggage, so make a copy of the array.int off = original.offset;v = Arrays.copyOfRange(originalValue, off, off+size);} else {// The array representing the String is the same// size as the String, so no point in making a copy.v = originalValue;}this.offset = 0;this.count = size;this.value = v;}

?

?

?3、傳入一個字符數組的構造函數

public String(char value[]) {int size = value.length;this.offset = 0;this.count = size;this.value = Arrays.copyOf(value, size);}

?

?

4、傳入一個字符串數字,和開始元素,元素個數的構造函數

public String(char value[], int offset, int count) {if (offset < 0) {throw new StringIndexOutOfBoundsException(offset);}if (count < 0) {throw new StringIndexOutOfBoundsException(count);}// Note: offset or count might be near -1>>>1.if (offset > value.length - count) {throw new StringIndexOutOfBoundsException(offset + count);}this.offset = 0;this.count = count;this.value = Arrays.copyOfRange(value, offset, offset+count);}

?

?  由上面的幾個常見的構造函數可以看出,我們在生成一個String對象的時候必須對該對象的offset、count、value三個屬性進行賦值,這樣我們才能獲得一個完成的String類型。

?


?

常見函數:

?

1、判斷兩個字符串是否相等的函數(Equal):其實就是首先判斷比較的實例是否是String類型數據,不是則返回False,是則比較他們每一個字符元素是否相同,如果都相同則返回True,否則返回False

public boolean equals(Object anObject) {if (this == anObject) {return true;}if (anObject instanceof String) {String anotherString = (String)anObject;int n = count;if (n == anotherString.count) {char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;while (n-- != 0) {if (v1[i++] != v2[j++])return false;}return true;}}return false;}

?

?

?2、比較兩個字符串大小的函數(compareTo):輸入是兩個字符串,返回的0代表兩個字符串值相同,返回小于0則是第一個字符串的值小于第二個字符串的值,大于0則表示第一個字符串的值大于第二個字符串的值。

  比較的過程主要如下:從兩個字符串的第一個元素開始比較,實際比較的是兩個char的ACII碼,加入有不同的值,就返回第一個不同值的差值,否則返回0

public int compareTo(String anotherString) {int len1 = count;int len2 = anotherString.count;int n = Math.min(len1, len2);char v1[] = value;char v2[] = anotherString.value;int i = offset;int j = anotherString.offset;if (i == j) {int k = i;int lim = n + i;while (k < lim) {char c1 = v1[k];char c2 = v2[k];if (c1 != c2) {return c1 - c2;}k++;}} else {while (n-- != 0) {char c1 = v1[i++];char c2 = v2[j++];if (c1 != c2) {return c1 - c2;}}}return len1 - len2;}
View Code

?

?

?3、判斷一個字符串是否以prefix字符串開頭,toffset是相同的長度

public boolean startsWith(String prefix, int toffset) {char ta[] = value;int to = offset + toffset;char pa[] = prefix.value;int po = prefix.offset;int pc = prefix.count;// Note: toffset might be near -1>>>1.if ((toffset < 0) || (toffset > count - pc)) {return false;}while (--pc >= 0) {if (ta[to++] != pa[po++]) {return false;}}return true;}public int hashCode() {int h = hash;if (h == 0) {int off = offset;char val[] = value;int len = count;for (int i = 0; i < len; i++) {h = 31*h + val[off++];}hash = h;}return h;}

?

?

?4、連接兩個字符串(concat)

public String concat(String str) {int otherLen = str.length();if (otherLen == 0) {return this;}char buf[] = new char[count + otherLen];getChars(0, count, buf, 0);str.getChars(0, otherLen, buf, count);return new String(0, count + otherLen, buf);}

?

?

?連接字符串的幾種方式

1、最直接,直接用+連接

     String a = new String("bb");String b = new String("aa");String c =  a + b;

?

?

?2、使用concat(String)方法

      String a = new String("bb");String b = new String("aa"); String d = a.concat(b);

?

?

3、使用StringBuilder

 String a = new String("bb");String b = new String("aa");StringBuffer buffer = new StringBuffer().append(a).append(b);

?

?  第一二中用得比較多,但效率比較差,使用StringBuilder拼接的效率較高。

?

轉載于:https://www.cnblogs.com/0201zcr/p/4621339.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/258648.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/258648.shtml
英文地址,請注明出處:http://en.pswp.cn/news/258648.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python在材料模擬中的應用_基于Python的ABAQUS二次開發及在板料快速沖壓成形模擬中的應用...

2009doi:1013969/j1issn1100722012120091041013基于Python的ABAQUS二次開發及在板料快速沖壓成形模擬中的應用(北京航空航天大學飛行器制造工程系,北京100191)吳向東劉志剛萬敏王文平黃霖摘要:采用Python腳本語言對ABAQUS的前處理模塊進行二次開發,討論了Python腳本在ABAQUS二次…

Doxygen簡介

&#xff08;轉自&#xff1a;http://www.cnblogs.com/liuliunumberone/archive/2012/04/10/2441391.html&#xff09; 一&#xff0e;什么是Doxygen? Doxygen 是一個程序的文件產生工具&#xff0c;可將程序中的特定批注轉換成為說明文件。通常我們在寫程序時&#xff0c;或多…

javascript之閉包理解以及應用場景

1 function fn(){2 var a 0;3 return function (){4 return a;5 } 6 }如上所示&#xff0c;上面第一個return返回的就是一個閉包&#xff0c;那么本質上說閉包就是一個函數。那么返回這個函數有什么用呢&#xff1f;那是因為這個函數可以調用到它外部的a…

faster rcnn學習之rpn、fast rcnn數據準備說明

在上文《 faster-rcnn系列學習之準備數據》,我們已經介紹了imdb與roidb的一些情況&#xff0c;下面我們準備再繼續說一下rpn階段和fast rcnn階段的數據準備整個處理流程。 由于這兩個階段的數據準備有些重合&#xff0c;所以放在一起說明。 我們并行地從train_rpn與train_fas…

sql server規范

常見的字段類型選擇 1.字符類型建議采用varchar/nvarchar數據類型2.金額貨幣建議采用money數據類型3.科學計數建議采用numeric數據類型4.自增長標識建議采用bigint數據類型 (數據量一大&#xff0c;用int類型就裝不下&#xff0c;那以后改造就麻煩了)5.時間類型建議采用為dat…

關于標準庫中的ptr_fun/binary_function/bind1st/bind2nd

http://www.cnblogs.com/shootingstars/archive/2008/11/14/860042.html 以前使用bind1st以及bind2nd很少&#xff0c;后來發現這兩個函數還挺好玩的&#xff0c;于是關心上了。在C Primer對于bind函數的描述如下&#xff1a;“綁定器binder通過把二元函數對象的一個實參綁定到…

CSS偽類

一、首字母的顏色字體寫法 p:first-letter 二、文本的特殊樣式設置 first-line css偽類可與css類配合使用 偽元素只能用于塊級元素 轉載于:https://www.cnblogs.com/boyblog/p/4623374.html

php 結構體_【開發規范】PHP編碼開發規范下篇:PSR-2編碼風格規范

之前的一篇文章是對PSR-1的基本介紹接下來是PSR-2 編碼風格規范&#xff0c;它是 PSR-1 基本代碼規范的繼承與擴展。PSR-1 和PSR-2是PHP開發中基本的編碼規范&#xff0c;大家其實都可以參考學習下&#xff0c;雖然說每個開發者都有自己熟悉的一套開發規范&#xff0c;但是我覺…

faster rcnn學習之rpn訓練全過程

上篇我們講解了rpn與fast rcnn的數據準備階段&#xff0c;接下來我們講解rpn的整個訓練過程。最后 講解rpn訓練完畢后rpn的生成。 我們順著stage1_rpn_train.pt的內容講解。 name: "VGG_CNN_M_1024" layer {name: input-datatype: Pythontop: datatop: im_infotop: …

BitMapData知識 轉

Bitmap和BitmapData 2010.5.25 smartblack整理 一、flash.display.Bitmap類及其兩個子類 1、繼承自DisplayObject&#xff0c;和InteractiveObject平級&#xff0c;所以無法調度鼠標事件&#xff0c;可以使用額外的包裝容器(Sprite)來實現偵聽。 2、只支持GIF、JPEG、PNG格式&a…

Android學習之高德地圖的通用功能開發步驟(二)

周一又來了&#xff0c;我就接著上次的開發步驟&#xff08;一&#xff09;來吧&#xff0c;繼續把高德地圖的相關簡單功能分享一下 上次寫到了第六步&#xff0c;接著寫第七步吧。 第七步&#xff1a;定位 地圖選點 路徑規劃 實時導航 以下是我的這個功能NaviMapActivity的…

Oracle中分區表中表空間屬性

Oracle中的分區表是Oracle中的一個很好的特性&#xff0c;可以把大表劃分成多個小表&#xff0c;從而提高對于該大表的SQL執行效率&#xff0c;而各個分區對應用又是透明的。分區表中的每個分區有獨立的存儲特性&#xff0c;包括表空間、PCT_FREE等。那分區表中的各分區表空間之…

期刊論文格式模板 電子版_期刊論文的框架結構

最近看到很火的一句話&#xff0c;若不是生活所迫&#xff0c;誰愿意把自己弄得一身才華。是否像極了正想埋頭苦寫卻毫無頭緒的你&#xff1f;發表期刊論文的用途 &#xff1a;1: 學校或者單位評獎&#xff0c;評優&#xff0c;推免等2&#xff1a;申領學位證(如畢業硬性要求&a…

faster rcnn學習之rpn 的生成

接著上一節《 faster rcnn學習之rpn訓練全過程》&#xff0c;假定我們已經訓好了rpn網絡&#xff0c;下面我們看看如何利用訓練好的rpn網絡生成proposal. 其網絡為rpn_test.pt # Enter your network definition here. # Use ShiftEnter to update the visualization. name: &q…

初學java之常用組件

1 2 import javax.swing.*;3 4 import java.awt.*;5 class Win extends JFrame6 {7 JTextField mytext; // 設置一個文本區8 JButton mybutton;9 JCheckBox mycheckBox[]; 10 JRadioButton myradio[]; 11 ButtonGroup group; //為一…

anaconda 安裝在c盤_最省心的Python版本和第三方庫管理——初探Anaconda

打算把公眾號和知乎專欄的文章搬運一點過來。 歷史文章可以去關注我的公眾號&#xff1a;不二小段&#xff0c;或者知乎&#xff1a;段小草。也歡迎來看我的視頻學Python↓↓↓跟不二學Python這篇文章可以作為Python入門的第一站可以結合這期視頻來看&#xff0c;基本上是這期視…

Iris recognition papers in the top journals in 2017

轉載自&#xff1a;https://kiennguyenstuff.wordpress.com/2017/10/05/iris-recognition-papers-in-the-top-journals-in-2017/ Top journals: – IEEE Transaction on Pattern Analysis and Machine Intelligence (PAMI) – Pattern Recognition (PR) – IEEE Transaction on…

判斷瀏覽器是否為IE內核的最簡單的方法

沒啥說的&#xff0c;直接貼代碼&#xff0c;算是ie hack了。 if (![1,]) {alert(is ie); } 轉載于:https://www.cnblogs.com/jasondan/p/3716660.html

dubbo控制中心部署,權重配置,以及管控臺中各個配置的簡單查看

dubbo給我們提供了現成的后臺管理網站&#xff0c;專門管理這些服務&#xff0c;應用&#xff0c;路由規則&#xff0c;動態配置&#xff0c;訪問控制、權重控制、負載均衡等等&#xff0c;還可以查看系統日志&#xff0c;系統狀態&#xff0c;系統環境等等&#xff0c;功能很是…

給git配置http代理

1. 安裝socat apt-get install socat 2. 創建配置文件&#xff0c;取名gitproxy填入以下內容&#xff1a; #!/bin/sh_proxy135.245.48.33_proxyport8000 exec socat STDIO PROXY:$_proxy:$1:$2,proxyport$_proxyport 加上可執行權限chmod x gitproxy&#xff0c;將此文件放在環…