`
zhouxiaoli521
  • 浏览: 554054 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

StringBuffer的setLength

    博客分类:
  • java
 
阅读更多

经常用stringbuffer来代替string 一般都是在循环中使用 我在下一次使用时会调用setLength(0)已清空字符串

今天我偶然在debug中查看stringbuffer 

惊讶的发现 原来我以前对setLength的理解是错误的

我以前认为length为x 就保留x个char 

但事实是 设置setLength后 sb中的char一个都没有删除 全部保留了 它只是把内部属性count设置为x

如果你写入新的字符会把之前的字符覆盖

所以如果你之前有一个很长的字符串在stringbuffer中 想要清除的话 就要用delete(start, end)

分享到:
评论
3 楼 zhouxiaoli521 2013-12-05  
zhouxiaoli521 写道
weinifk 写道
public static void main(String[] args) {
StringBuffer test = new StringBuffer("");
test.append("abcdefhhijklmnopqrstuvwxyz");
System.out.println("length:" + test.length() + test.toString());
test.setLength(0);
test.append("wolegequde...");
System.out.println("length:" + test.length() + test.toString());
//test.delete(0, test.length());
}


输出结果:
length:26abcdefhhijklmnopqrstuvwxyz
length:13wolegequde...

   public void setLength(int newLength) {
 if (newLength < 0)
     throw new StringIndexOutOfBoundsException(newLength);
 if (newLength > value.length)
     expandCapacity(newLength);

 if (count < newLength) {
     for (; count < newLength; count++)
  value[count] = '\0';
 } else {
            count = newLength;
        }
    }


最简单的方式 debug看一下value里的值
2 楼 zhouxiaoli521 2013-12-05  
weinifk 写道
public static void main(String[] args) {
StringBuffer test = new StringBuffer("");
test.append("abcdefhhijklmnopqrstuvwxyz");
System.out.println("length:" + test.length() + test.toString());
test.setLength(0);
test.append("wolegequde...");
System.out.println("length:" + test.length() + test.toString());
//test.delete(0, test.length());
}


输出结果:
length:26abcdefhhijklmnopqrstuvwxyz
length:13wolegequde...

   public void setLength(int newLength) {
 if (newLength < 0)
     throw new StringIndexOutOfBoundsException(newLength);
 if (newLength > value.length)
     expandCapacity(newLength);

 if (count < newLength) {
     for (; count < newLength; count++)
  value[count] = '\0';
 } else {
            count = newLength;
        }
    }
1 楼 weinifk 2013-12-04  
public static void main(String[] args) {
StringBuffer test = new StringBuffer("");
test.append("abcdefhhijklmnopqrstuvwxyz");
System.out.println("length:" + test.length() + test.toString());
test.setLength(0);
test.append("wolegequde...");
System.out.println("length:" + test.length() + test.toString());
//test.delete(0, test.length());
}


输出结果:
length:26abcdefhhijklmnopqrstuvwxyz
length:13wolegequde...

相关推荐

Global site tag (gtag.js) - Google Analytics