面试题:关于StringBuffer()源码的深度理解Debug分析
发布日期:2021-05-08 23:17:20 浏览次数:16 分类:博客文章

本文共 1712 字,大约阅读时间需要 5 分钟。

 

 

import org.junit.Test;/** * @author CH * @create 2021 上午 11:23 */public class IDEADebug {    @Test    public void testStringBuffer(){        String str = null;        StringBuffer sb = new StringBuffer();        sb.append(str);//把null当4个字母添加进去        System.out.println(sb.length());//4        System.out.println(sb);//"null"        StringBuffer sb1 = new StringBuffer(str);//抛异常NullPointerException空指针异常        System.out.println(sb1);//    }}

 

 问题:

为什么 sb.append(str)后的str.length是4?

 

 

 

 进入StringBuffer()方法:

 

 

 

 

 

 

 

下一行:

 

 

 进入super.append(str);

 

 

 

 

进入return appendNull();

 

 

 

 

 

 进入StringBuffer()

 

 

 

.length所以是空指针异常

 

 

附录:

 

/**  * Constructs a string buffer with no characters in it and  * the specified initial capacity.  *  * @param      capacity  the initial capacity.  * @exception  NegativeArraySizeException  if the {@code capacity}  *               argument is less than {@code 0}.  */ public StringBuffer(int capacity) {     super(capacity); } /**  * Constructs a string buffer initialized to the contents of the  * specified string. The initial capacity of the string buffer is  * {@code 16} plus the length of the string argument.  *  * @param   str   the initial contents of the buffer.  */ public StringBuffer(String str) {     super(str.length() + 16);     append(str); }

StringBuffer类 

StringBuffer 类不同于String ,其对象必须使用构造器生成。有 三 个 构造 器 :
StringBuffer() :初始为 容量为16 的字符串缓冲区
StringBuffer(int size) :构造 指定容量的字符串缓冲区
StringBuffer(String str) :将内容初始化为指定字符串内容

   

StringBuffer 类的常用方法

StringBuffer append(xxx):提供了很多的append()方法,用于进行字符串拼接
StringBuffer delete(int start,int end):删除指定位置的内容
StringBuffer replace(int start, int end, String str):把[start,end)位置替换为str
StringBuffer insert(int offset, xxx):在指定位置插入xxx
StringBuffer reverse() :把当前字符序列逆转

 

上一篇:Calendar日历类(抽象类)的使用
下一篇:算法题:获取两个字符串中的最大相同子串

发表评论

最新留言

很好
[***.229.124.182]2025年03月30日 19时26分33秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章