5

我试图了解 ajava String的实现方式。jdk7 source下面的代码显示了对originalValue.length > size.是否有可能设计一个字符串参数来使这个检查为真?

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;
    }
...
}
4

2 回答 2

3

看看这段代码:

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

第二个构造函数将匹配条件。诀窍在于子字符串方法。它不会生成真正的子字符串,而是复制底层数组并为其设置新边界。构造一个新字符串的想法是复制一个字符串,而不仅仅是分配同一个数组。这实际上就是为什么从大字符串中提取小子字符串可能会导致 OOM 异常的原因。因为要表示一小块信息,使用了大数组。

于 2013-08-17T06:04:15.483 回答
3

你可以调试这个。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
于 2013-08-17T06:04:55.690 回答