Java中的StringBuffer类insert方法看不懂

图片中的函数看不懂while是怎么回事,调用函数是addZero(calendar.get(Calendar.HOUR),2)

图片说明

变量temp的位数不够len,就在它前面用0补齐

你求的是日历小时,比如 01时45分,while是补全那个零的。

楼主疑惑的是insert方法吗?

insert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.

这个方法简单,对时间中的小时数进行处理,
比如2017-3-4 7:35:45,对于这个时间,calendar.get(Calendar.HOUR)方法返回的结果是7,
**这个方法的作用是在7的前面加上数字0.

add的值是字符串“7”;
然后add.length()是1,len是2,所以while循环执行一次,
add.insert(0,0)意思是在add这个字符串的第0个位置插入数字0,
所以执行后add的值是字符串"07",最后把“07”返回.
**

意思就是如果你要传入的temp的长度如果小于2个长度,那么就在最前面通过加0字符串的方式补上去

    StringBuffer str = new StringBuffer("wweizhen");  
  System.out.println(str); //调用insert方法前结果:wweizhen
  str.insert(1,"ang");
  System.out.println(str); //调用insert方法后结果:wangweizhen
    注:当前数字是插入字符的位置,字符串的位置是从零开始的

比如 StringBuffer.insert(1,"zhang"); 将字符串zhang插入下标位1的位置
将指定的对象插入指定的位置