String和StringBuffer的substring()方法的比較

由于String类型不可修改,所以String类的substring()方法返回的是新串这点不意外

 

但是StringBuffer的截取功能返回值类型也不再是StringBuffer本身了,而是一个String类型对象,这点在初学的时候很意外。

再去看看StringBuffer中的substring()方法的实现,是通过下列方法new()出一个String对象作为返回值

@Override
    public synchronized String substring(int start, int end) {
        return super.substring(start, end);
    }
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);
    }

//StringBuffer很多的操作方法返回的都是其对象本身,substring()方法例外
 

 public String substring(int start)
//返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
 public String substring(int start,int end)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值