zoukankan      html  css  js  c++  java
  • 面试题:关于StringBuffer()源码的深度理解Debug分析

    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() :把当前字符序列逆转

    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    ASP.NET Web API 2 之文件下载
    Windows 查看某个端口号是否被占用
    C# 数据类型之 String(字符串)
    数据表对应关系(一对一、一对多、多对多)
    嫁给程序员的好处,你get到了吗?
    ASP.NET Web API 2 之 HttpRequestMessage 对象
    C# 使用 log4net 记录日志
    Chrome 浏览器快捷键
    C# 获取程序运行时路径
    SpringBoot整合Pagehelper分页插件
  • 原文地址:https://www.cnblogs.com/CCTVCHCH/p/14668851.html
Copyright © 2011-2022 走看看