java中常见面试题String,StringBuffer,StringBulider 的区别及相应的使用方法介绍

来源:互联网 发布:js点击显示隐藏div 编辑:程序博客网 时间:2024/06/10 13:10
String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。

字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。因为String 对象是不可变的,所以可以共享。例如:

String str = "abc";


等效于:


char data[] = {'a', 'b', 'c'};

String str = new String(data);

StringBuffer线程安全的可变字符序列。一个类似于 String 的字符串缓冲区,但不能修改。StringBuffer 上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符添加或插入到字符串缓冲区中。append 方法始终将这些字符添加到缓冲区的末端;而 insert 方法则在指定的点添加字符

StringBuilder一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。

  下面是个人写的测试代码可加深对其理解和记忆!

   一句话总结:String 声明初始化的内容是对象分配到共享内存中,StringBuffer是线程安全的速度比String快,StringBulider线程不安全但最快,大部分时可以采用!

package practice;import java.util.Date;public class Test1 {private static final String base = "测试";private static final int count = 1000000;public static void stringTest() {long begin, end;begin = System.currentTimeMillis();String test = new String(base);for (int i = 0; i < count / 100; i++) {test = test + "add";}end = System.currentTimeMillis();System.out.println((end - begin) + "millis(使用String消耗的时间)");}public static void stringBufferTest() {long begin, end;begin = System.currentTimeMillis();StringBuffer test = new StringBuffer(base);for (int i = 0; i < count; i++) {test = test.append("add");}end = System.currentTimeMillis();System.out.println((end - begin) + "millis(使用Stringbuffer消耗的时间)");}public static void stringBuliderTest() {long begin, end;begin = System.currentTimeMillis();StringBuilder test = new StringBuilder("base");for (int i = 0; i < count; i++) {test = test.append("add");}end = System.currentTimeMillis();System.out.println((end - begin) + "millis(使用StringBulider消耗的时间)");}public static void main(String[] args) {stringTest();System.out.println();stringBufferTest();System.out.println();stringBuliderTest();}}


原创粉丝点击