簡體   English   中英

java String構造函數邏輯

[英]java String constructor logic

我試圖了解java String是如何實現的。下面的jdk7 source代碼顯示了對originalValue.length > size的檢查。我無法弄清楚它是如何實現的。我試圖在一些java String創建時使用eclipse調試器語句,但這個檢查從來都不是真的。是否有可能設計一個String參數,使這個檢查成立?

public final class String{
    /** The value is used for character storage. */
    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. */
    private final int count;

    /** Cache the hash code for the string */
    private int hash; // Default to 0

     /**
     * Initializes a newly created {@code String} object so that it represents
     * the same sequence of characters as the argument; in other words, the
     * newly created string is a copy of the argument string. Unless an
     * explicit copy of {@code original} is needed, use of this constructor is
     * unnecessary since Strings are immutable.
     *
     * @param  original
     *         A {@code String}
     */
    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;
    }
...
}

看看這段代碼:

String s1 = "123456789";
String s2 = new String(s1.substring(0, 2));

第二個構造函數將匹配條件。 訣竅在於子串方法。 它不是一個真正的子串,而是復制底層數組,並為它設置新的邊界。 構造新字符串的想法是創建一個字符串的副本,而不僅僅是分配相同的數組。 這就是為什么從大字符串中獲取小子串可能導致OOM異常的原因。 因為代表一小塊信息使用大數組。

你可以調試這個。 Value表示底層char[] count代表view

 String s = new String("Hello   "); //value= [H, e, l, l, o, , , ]  count=8

 String os = s.trim();  //value= [H, e, l, l, o, , , ]  count=5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM