1. 程式人生 > >Java基礎3:String型別

Java基礎3:String型別

String(java.lang.String)

不可變性

  • public final class String{xxx…}
  • 以final修飾,表示String類不可被繼承
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
  • 內部為一個char陣列,也被初始化為final,一旦被初始化後就不可變。並且 String 內部沒有改變 value 陣列的方法,因此可以保證 String 不可變。

String的連線

@Test 
public void contact () { 
//1連線方式 String s1 = "a"; 
String s2 = "a"; 
String s3 = "a" + s2; 
String s4 = "a" + "a"; 
String s5 = s1 + s2; 
//表示式只有常量時,編譯期完成計算 
//表示式有變數時,執行期才計算,所以地址不一樣 
System.out.println(s3 == s4); //f 
System.out.println(s3 == s5); //f 
System.out.println(s4 == "aa"); //t 
}

String Pool

字串常量池(String Pool)儲存著所有字串字面量(literal strings),這些字面量在編譯時期就確定。不僅如此,還可以使用 String 的 intern() 方法在執行過程中將字串新增到 String Pool 中。

當一個字串呼叫 intern() 方法時,如果 String Pool 中已經存在一個字串和該字串值相等(使用 equals() 方法進行確定),那麼就會返回 String Pool 中字串的引用;否則,就會在 String Pool 中新增一個新的字串,並返回這個新字串的引用。

下面示例中,s1 和 s2 採用 new String() 的方式新建了兩個不同字串,而 s3 和 s4 是通過 s1.intern() 方法取得一個字串引用。intern() 首先把 s1 引用的字串放到 String Pool 中,然後返回這個字串引用。因此 s3 和 s4 引用的是同一個字串。

String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2);           // false
String s3 = s1.intern();
String s4 = s1.intern();
System.out.println(s3 == s4);           // true

如果是採用 “bbb” 這種字面量的形式建立字串,會自動地將字串放入 String Pool 中。

String s5 = "bbb";
String s6 = "bbb";
System.out.println(s5 == s6);  // true

String型別的intern

public void intern () { 
//2:string的intern使用 
//s1是基本型別,比較值。s2是string例項,比較例項地址 
//字串型別用equals方法比較時只會比較值 
String s1 = "a"; String s2 = new String("a"); 
//呼叫intern時,如果s2中的字元不在常量池,則加入常量池並返回常量的引用 
String s3 = s2.intern(); 
System.out.println(s1 == s2); 
System.out.println(s1 == s3);
 }

String型別的equals

//重寫Object的equals方法
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;
    }

String,StringBuffer,StringBuilder,以及對String不變性的理解

  • String、StringBuffer、StringBuilder

    • 都是 final 類,都不允許被繼承
    • String 長度是不可變的,StringBuffer、StringBuilder 長度是可變的
    • StringBuffer 是執行緒安全的,StringBuilder 不是執行緒安全的,但它們兩個中的所有方法都是相同的,StringBuffer 在 StringBuilder 的方法之上添加了 synchronized 修飾,保證執行緒安全
    • StringBuilder 比 StringBuffer 擁有更好的效能
    • 如果一個 String 型別的字串,在編譯時就可以確定是一個字串常量,則編譯完成之後,字串會自動拼接成一個常量。此時 String 的速度比 StringBuffer 和 StringBuilder 的效能好的多
  • String 不變性的理解

    • String 類是被 final 進行修飾的,不能被繼承
    • 在用 + 號連結字串的時候會建立新的字串
    • String s = new String(“Hello world”); 可能建立兩個物件也可能建立一個物件。如果靜態區中有 “Hello world” 字串常量物件的話,則僅僅在堆中建立一個物件。如果靜態區中沒有 “Hello world” 物件,則堆上和靜態區中都需要建立物件。
    • 在 Java 中, 通過使用 “+” 符號來串聯字串的時候,,實際上底層會轉成通過 StringBuilder 例項的 append() 方法來實現。

StringBuilder,StringBuffer底層

append

/**
     * The value is used for character storage.
     */
    char[] value;
    //初始化容量為16

    /**
     * Constructs a string builder with no characters in it and an * initial capacity of 16 characters.
     */
    public StringBuilder() {
        super(16);
    }

    //這兩個類的append方法都是來自父類AbstractStringBuilder的方法

    public AbstractStringBuilder append(String str) {
        if (str == null) return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

    @Override
    public StringBuilder append(String str) {
        super.append(str);
        return this;
    }

    @Override
    public synchronized StringBuffer append(String str) {
        toStringCache = null;
        super.append(str);
        return this;
    }

擴容

//注意在append方法中呼叫到了一個函式
    //ensureCapacityInternal(count +len);
    //該方法是計算append之後的空間是否足夠,不足的話需要進行擴容

    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0) ensureCapacityInternal(minimumCapacity);
    }

    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code 
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value, newCapacity(minimumCapacity));
        }
    }
    //如果新字串長度大於value陣列長度則進行擴容 擴容後的長度一般為原來的兩倍 + 2; 
    //假如擴容後的長度超過了jvm支援的最大陣列長度MAX_ARRAY_SIZE。
    //考慮兩種情況 如果新的字串長度超過int最大值,則丟擲異常,否則直接使用陣列最大長度作為新陣列的長度。

    private int hugeCapacity(int minCapacity) {
        if (Integer.MAX_VALUE - minCapacity < 0) {
            // overflow
            throw new OutOfMemoryError();
        }
        return (minCapacity > MAX_ARRAY_SIZE) ? minCapacity : MAX_ARRAY_SIZE;
    }

刪除

//這兩個型別的刪除操作:都是呼叫父類的delete方法進行刪除

    public AbstractStringBuilder delete(int start, int end) {
        if (start < 0) throw new StringIndexOutOfBoundsException(start);
        if (end > count) end = count;
        if (start > end) throw new StringIndexOutOfBoundsException();
        int len = end - start;
        if (len > 0) {
            System.arraycopy(value, start + len, value, start, count - end);
            count -= len;
        }
        return this;
    }

    //事實上是將剩餘的字元重新拷貝到字元陣列value。

用到了system.arraycopy來拷貝陣列,速度是比較快的