String、StringBuffer、StringBuilder的区别

   今天,和同学说后2者的时候,把特性说反了。自己也觉得好像有点不对。那么我就直接翻了官方源码!发现,我确实是讲错了!为了让自己更加清除!我就写一篇学习日志把!我也是小白,说得不好的地方请大牛指正!

1.String:字符串类
a.字符串的定义:4种方式
    
    String name1 = "hello";
    String name2 = new String("hello");
    char [] chary ={'h','e','l','l','o'};
    String name3 = new String(chary);
    字符串本质上就是一个的字符数组,而每一个字符
    对应一个ASCII,而ASCII的取值范围-128到127
    byte [] buf = {72,69,76,76,79};
    String name4 = new String(buf);
  b.字符串如何转换成 char数组 byte 数组。  
    char [] ch = name1.toCharArray();
<span style="white-space:pre">	</span>byte [] buf1 = name1.getBytes();
  c.字符串的比较。
    ==     比较的是地址是否相同。
    equals 比较的是两个字符串的内容是否相同。 
    
    String name1 = "nihao";
    String name2 = new String(name1);
    字符串本质上就是一堆的ASCII码组成的。而
    ASCII是常量,而常量开辟内存在栈区的常量池
    中,而字符串最初都是在常量池中构造出来的。
    常量池中的内容有一个特点,一旦有一个nihao
    就不会产生另一个nihao,唯一性。
    +的本质,并不是将一个字符串拼接到另一个字符串
    的后面,而是在堆区重新开辟内存。
    
    字符串最初构造在常量池,因此,字符串具有常量
    的特点:不变性。
    而+号会要在堆区开辟内存,因此如果频繁对字符串
    做+的操作,是要消耗内存的,减低性能的。
    
    所以,如果要做字符串频繁的+的操作,请用下两者

2.StringBuffer:
     jdk1.1的时候出现
     带有缓冲的字符串类。初始化容量是16字符,
  如果有其他字符拼接,是追加到字符串的后面。
  这个字符串的容量是以一倍的形式扩充。
  append();
   源代码我不贴出来了,里面大多的方法都是使用了同步代码块关键字synchronized,因此,它的这些追加方法,是线程安全的。那么就会失去性能!后来为了效率,出现了
   StringBuilder

3.StringBuilder:
  我们先来看看源代码:该类,是jdk1.5的时候才有的。并且和StringBuffer功能上差不多,而且该类其中的所有方法都没有同步代码块,所以是非线程安全的,那么这样的话,和StringBuffer相比追加字符串的时候就会更加效率!
<pre name="code" class="java">/**
 * A modifiable {@link CharSequence sequence of characters} for use in creating
 * strings. This class is intended as a direct replacement of
 * {@link StringBuffer} for non-concurrent use; unlike {@code StringBuffer} this
 * class is not synchronized.
 *
 * <p>For particularly complex string-building needs, consider {@link java.util.Formatter}.
 *
 * <p>The majority of the modification methods on this class return {@code
 * this} so that method calls can be chained together. For example:
 * {@code new StringBuilder("a").append("b").append("c").toString()}.
 *
 * @see CharSequence
 * @see Appendable
 * @see StringBuffer
 * @see String
 * @see String#format
 * @since 1.5
 */
public final class StringBuilder extends AbstractStringBuilder implements
        Appendable, CharSequence, Serializable {

    private static final long serialVersionUID = 4383685877147921099L;

    /**
     * Constructs an instance with an initial capacity of {@code 16}.   //初始容量16,和StringBuffer一样
     *

 
   具体用到什么地方:当我们在对流的操作的时候,我们就可以使用StringBuffer或者StringBuilder,代替String类。这样会提高效率哦。
到这里,我想你肯定熟悉这3个类的了。那就自己试试把!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值