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

    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    LeetCode子集问题
    面试题-求最大字典区间
    链表快速排序
    树的非递归遍历
    快速排序非递归实现
    leetcode217 python3 72ms 存在重复元素
    leetcode121 C++ 12ms 买股票的最佳时机 只能买卖一次
    leetcode1 python3 76ms twoSum 360面试题
    leetcode485 python3 88ms 最大连续1的个数
    leetcode119 C++ 0ms 杨辉三角2
  • 原文地址:https://www.cnblogs.com/CCTVCHCH/p/14668851.html
Copyright © 2011-2022 走看看