java內部的字符串類型是通過對象來進行管理的,分為String類,StringBuffer類,以及StringBuilder類。三個類都實現了CharSequence[^CharSequence]接口,在java.lang中定義并被聲明為final。
String類型實現了CharSequence[^CharSequence],Serializable[^Serializable],Comparable[^Comparable]三個接口,源碼中主要的變量有兩個:value[]和hash。
PRivate final char value[];private int hash;從上可以看出String類型是使用一個被聲明為final的char數組來存儲字符串,因此String類型的對象在聲明之后不可更改 (注意雖然String類型聲明后不可更改,但String類型的引用可以隨時更換引用對象)
String name="abc";name="def";//name改變了引用的對象,但是在沒有進行垃圾回收前//內存中仍然存在著"abc","def"兩個字符串實例String類型內部有超過十種的構造函數,其中比較特殊的有以下幾種: 1.String(char value[])
public String(char value[]) { this.value = Arrays.copyOf(value, value.length);//調用Arrays的copyOf()方法拷貝數組 }2.String(char value[], int offset, int count)
public String(char value[], int offset, int count) {//指定了數組中的開始和結尾 if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count <= 0) { if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset <= value.length) { this.value = "".value; return; } } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.value = Arrays.copyOfRange(value, offset, offset+count); }3.String(byte bytes[], int offset, int length, Charset charset)
public String(byte bytes[], int offset, int length, Charset charset) { //指定特殊的字符集來講bytes數組中的一部分轉換為字符串 if (charset == null) throw new NullPointerException("charset"); checkBounds(bytes, offset, length); //檢查指定的子數組是否越界 this.value = StringCoding.decode(charset, bytes, offset, length); }1.獲取字符串長度的函數length()
public int length() { //返回數組的長度 return value.length; }2.除了new顯示構造一個String實例,也可以直接將字符串字面值當做對象使用
System.out.println("abc".length());//結果顯示為33.一般來說,Java不允許對字符串對象使用運算符,但可以使用“+”號來連接字符串,會以生成一個新的字符串對象作為結果。 同時,也可以使用“+”號來連接字符串與非字符串對象,編譯器會自動將非字符串類型轉換為字符串類型操作(因此在字符串與其他類型在一起的時候要特別小心)
System.out.println("abc"+"def");//結果顯示為abcdef//注意由于String類型的特點,此時內存里有abc,def,abcdef三個字符串實例System.out.println("abc"+3+3);//結果為abc33而不是abc6在上面的連接操作中,Java實際上調用了String的類型轉換方法valueOf()方法來實現的
public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); }可見實際上是調用了Object類型的toString()方法(因此可以通過重載子類型的toString()方法來改變valueOf()的結果)
對字符串操作的其中一大部分就是對其中部分字符的提取,String類型中提供了大量的提取字符的方法。 1.charAt(int index)提取單個位置的字符
public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }2.public 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); //調用System的arraycopy方法 }[1]:
新聞熱點
疑難解答