对象修改的差异

2023-11-30

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

    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。我注意到也有一些 Time 和 Date 类。我怎样才能弄清楚,什么时候将修改原始对象(在本例中是 s) )。这与对象的可变性有关吗?有什么一般规则吗? 提前致谢 香港


如果您看到substring方法定义在AbstractStringBuilder抽象类,后来扩展为StringBuilder类,你会发现下面的代码:

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对象将被返回。

现在如果你看到delete里面的方法定义StringBuilder类是:

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

以及删除的定义AbstractStringBuilder (StringBuilder超类)是:

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对象内容,并且它不返回新对象,而是返回传递给它的相同对象引用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对象修改的差异 的相关文章

随机推荐