
面试题:关于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)位置替换为strStringBuffer insert(int offset, xxx):在指定位置插入xxxStringBuffer reverse() :把当前字符序列逆转
发表评论
最新留言
很好
[***.229.124.182]2025年03月30日 19时26分33秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
python去除字符串中的特殊字符(爬虫存储数据时会遇到不能作为文件名的字符串)
2021-05-09
SpringCloud微服务(03):Hystrix组件,实现服务熔断
2021-05-09
Spring 框架基础(01):核心组件总结,基础环境搭建
2021-05-09
Cassandra数据建模
2021-05-09
Internet Explorer 10 专题上线
2021-05-09
云计算之路-阿里云上:0:25~0:40网络存储故障造成网站不能正常访问
2021-05-09
网站故障公告1:使用阿里云RDS之后一个让人欲哭无泪的下午
2021-05-09
上周热点回顾(6.3-6.9)
2021-05-09
上周热点回顾(8.12-8.18)
2021-05-09
【故障公告】升级阿里云 RDS SQL Server 实例故障经过
2021-05-09
蹒跚来迟:新版博客后台上线公测
2021-05-09
[网站公告]11月26日00:00-04:00阿里云RDS升级
2021-05-09
[网站公告]又拍云API故障造成图片无法上传(已恢复)
2021-05-09
云计算之路-阿里云上:“黑色30秒”走了,“黑色1秒”来了,真相也许大白了
2021-05-09
上周热点回顾(6.9-6.15)
2021-05-09
上周热点回顾(10.20-10.26)
2021-05-09
上周热点回顾(2.16-2.22)
2021-05-09
上周热点回顾(3.2-3.8)
2021-05-09
.NET跨平台之旅:借助ASP.NET 5 Beta5的新特性显示CLR与操作系统信息
2021-05-09
上周热点回顾(7.27-8.2)
2021-05-09