对象修改的差异

Differences in Object modifications

我只是想知道是否有人可以帮助我解决这个问题:

    StringBuilder s=new StringBuilder("0123456789");
    s.substring(1, 2);
    System.out.println(s);
    s.delete(2, 8);
    System.out.println(s);

第一个 Sysout 给出了 0123456789(虽然我期待一个子字符串)但是其他 Sysout 给出了 0189。我注意到还有一些时间和日期 classes.How 我可以弄清楚什么时候要修改什么形式原始对象(在本例中为 s)。这与对象的可变性有关吗?有什么一般规则吗? 提前致谢 香港

Javadoc 告诉您方法是否修改了它所操作的实例。

substring

Returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end - 1.

delete

Removes the characters in a substring of this sequence. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. If start is equal to end, no changes are made.

因此 substring 不会更改 StringBuilder 的状态,而 delete 会。

@Hauptman Koening

用你自己的例子试试这个,希望它会澄清

    StringBuilder s = new StringBuilder("0123456789");
    String substring = s.substring(1, 2); // See here it returns a String, remember Strings are constants i.e. not mutable, not modifying the original StringBuilder s
    System.out.println(substring);
    StringBuilder delete = s.delete(2, 8); // see here it returns the String Builder, so remember StringBuilder is a mutable sequence of characters, hence modified the original
    System.out.println(delete);

如果你在 AbstractStringBuilder 摘要 class 中看到 substring 方法定义,后来被 StringBuilder class 扩展,你会发现下面的代码:

public String substring(int start, int end) {
    if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (end > count)
        throw new StringIndexOutOfBoundsException(end);
    if (start > end)
        throw new StringIndexOutOfBoundsException(end - start);
    return new String(value, start, end - start);
}

从方法定义中您可以看到它正在返回一个新的 String 对象,该方法不适用于实际的 StringBuilder 内容。所以他们不会改变 StringBuilder 对象的内容,而是返回一个新的 String 对象。

现在,如果您在 StringBuilder class 中看到 delete 方法定义,它是:

@Override
public StringBuilder delete(int start, int end) {
    super.delete(start, end);
    return this;
}

AbstractStringBuilder(StringBuilder super class)中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;
}

从方法定义中可以清楚地了解到,它正在处理相同的 StringBuilder 对象内容,它不是返回一个新对象,而是返回传递给它的相同对象引用。