繁体   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