StringBuffer和StringBuilder调用append(null)方法的值的误导

package com;

public class StringTest2
{
    public static void main(String[] args)
    {
        StringBuffer sb = new StringBuffer();
        String s = null;
        sb.append(s);
        System.out.println(sb.length());
        StringBuilder sb2 = new StringBuilder();
        sb2.append(s);
        System.out.println(sb2.length());
    }

}

果会输出,有人一定会说输出0.

结果是什么呢?

4
null
4

怎么回事呢,明明添加了一个null值,结果竟然是4。

让我们来看看append方法的源码就知道了.
StringBuilder:

// Appends the specified string builder to this sequence.
    private StringBuilder append(StringBuilder sb) {
    if (sb == null)
            return append("null");
    int len = sb.length();
    int newcount = count + len;
    if (newcount > value.length)
        expandCapacity(newcount);
    sb.getChars(0, len, value, count);
    count = newcount;
        return this;
    }

StringBuffer的append方法是在它的父类中实现的:

public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
        int len = str.length();
    if (len == 0) return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    str.getChars(0, len, value, count);
    count = newCount;
    return this;
    }

这两个append方法都有共同的:

if (str == null) str = "null";
        int len = str.length();

如果str 是 null,就賦予str = "null" 这个字符串,而不是null了.
而"null"这个字符串的长度自然是4了.

 

转载自:http://blog.sina.com.cn/s/blog_4ee6ad380100axq3.html

### 关于 `StringBuffer` `StringBuilder` 是否包含 `String` 类的方法 在 Java 中,`StringBuffer` `StringBuilder` 并未直接继承自 `String` 类[^3]。实际上,它们都实现了 `CharSequence` 接口,并且提供了许多类似于 `String` 的操作方法,比如 `append()`、`insert()`、`delete()` 等[^1]。然而,这些方法并不是通过继承获得的,而是因为它们的设计目标是为了提供可变字符序列的支持。 #### 方法支持情况 尽管 `StringBuffer` `StringBuilder` 提供了许多与 `String` 类似的功能,但它们并不完全包含所有的 `String` 方法。例如,`String` 类中的某些特定方法(如 `intern()` 或 `getBytes(Charset charset)`),并未被 `StringBuffer` `StringBuilder` 所实现[^4]。这是因为 `String` 是不可变对象,其设计初衷与其他两个类存在本质区别。 #### 继承关系分析 从继承结构来看,`StringBuffer` `StringBuilder` 都是从抽象基类 `AbstractStringBuilder` 派生而来,而该基类也没有继承自 `String`[^2]。因此,严格意义上讲,这两个类并没有直接或间接地继承任何来自 `String` 的方法。 ```java // AbstractStringBuilder的部分定义展示 public abstract class AbstractStringBuilder implements Appendable, CharSequence { // ... } // StringBufferStringBuilder的具体定义 public final class StringBuilder extends AbstractStringBuilder {...} public final class StringBuffer extends AbstractStringBuilder implements Serializable {...} ``` #### 使用建议 如果需要调用一些仅存在于 `String` 类中的独特功能,则可能需要先将 `StringBuffer` 或 `StringBuilder` 转换为 `String` 对象再执行相应操作。可以通过 `.toString()` 方法完成这一转换过程: ```java StringBuilder sb = new StringBuilder("example"); System.out.println(sb.toString().toUpperCase()); // 将内容转成大写形式 ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值