StringBuffer和StringBuilder添加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 == 0return 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了.

String、StringBufferStringBuilder都是Java中用于处理字符串的类。 String是一个不可变的字符串类,也就是说一旦创建了一个String对象,它的就不能被修改。每次对String进行修改操作时,都会创建一个新的String对象,这样会浪费内存空间时间。因此,当需要频繁地对字符串进行修改时,使用String并不高效。 StringBufferStringBuilder是可变的字符串类,它们可以被用来进行字符串的修改操作。StringBufferStringBuilder的主要区别在于StringBuffer是线程安全的,而StringBuilder是非线程安全的。这意味着在多线程环境下,如果有多个线程同时访问一个StringBuffer对象,它们是安全的;而多个线程同时访问一个StringBuilder对象时,可能会导致数据错乱。 使用StringBufferStringBuilder的场景通常是在需要频繁地对字符串进行修改的情况下。例如,在循环中拼接字符串、在递归函数中修改字符串等情况下,使用StringBufferStringBuilder可以提高性能。 如果需要将StringBufferStringBuilder转换为String对象,可以使用两种方式。一种是调用它们的toString()方法,将其转换为String对象。另一种是使用String的构造器String(StringBuffer buffer)来创建一个新的String对象,将StringBufferStringBuilder的内容复制到新的String对象中。 总结起来,String是不可变的字符串类,而StringBufferStringBuilder是可变的字符串类,适用于需要频繁修改字符串的场景。转换为String对象可以通过调用toString()方法或使用String的构造器来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值