String 和StringBuffer的区别

来源:互联网 发布:滴滴数据存储架构 编辑:程序博客网 时间:2024/05/29 02:58

JAVA 平台提供了两个类:String和StringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。这个String类提供了数值不可改 变的字符串。而这个StringBuffer类提供的字符串进行修改。当你知道字符数据要改变的时候你就可以使用StringBuffer。典型地,你可 以使用StringBuffers来动态构造字符数据。

String str = "hello";

str = str + "world";

hello  和   hello world 是两个对象   hello字符串也许以后永远都不会再被用到,但这个字符串并不会被垃圾回收,因为它将一直存在于字符串池中—这也是JAVA内存泄露的原因之一。

对于 String 类而言,它代表字符串序列不可改变的字符串,因此如果程序需要一个字符序列会发生改变的字符串,那应该考虑使用StringBuilder或StringBuffer.很多资料上都推荐使用StringBuffer,那是因为这些资料都是JDK1.5问世之前的—过时了。

 实际上通常应该优先使用的是StringBuilder。StringBuffer是线程安全的,也就是说StringBuffer类里绝大部分方法都增加了synchronized修饰符。对方法增加synchronized修饰符可以保证该方法线程安全,但会降低该方法的执行效率。在没有多线程的环境下,应该优先使用StringBuilder类来表示字符串。

验证代码如下

/*  * Copyright (c) 2013, 360buy Group and/or its affiliates. All rights reserved. */package com.yh.java.mianshi;/** *  * @version 2013-11-19 * @author dbyanghao */public class StringStringbufferTest {/** * @param args */public static void main(String[] args) {//string 开始//定义一个字符串变量String  str = "Hello ";//identityHashCode方法用户获取某个对象唯一的hashCode值,只有当两个对象相同时,它们的identityHashCode才会相等System.out.println("String:"+str+"---"+System.identityHashCode(str));str = str + "World";System.out.println("String:"+str+"---"+System.identityHashCode(str));str = str + ", China";System.out.println("String:"+str+"---"+System.identityHashCode(str));//StringBufferStringBuffer stb = new StringBuffer("Hello ");System.out.println("StringBuffer:"+stb+"---"+System.identityHashCode(str));//追加更改字符串stb.append("World");System.out.println("StringBuffer:"+stb+"---"+System.identityHashCode(str));stb.append(", China");System.out.println("StringBuffer:"+stb+"---"+System.identityHashCode(str));//StringBuilderStringBuilder sbr = new StringBuilder("Hello ");System.out.println("StringBuilder:"+sbr+"---"+System.identityHashCode(str));//追加更改字符串sbr.append("World");System.out.println("StringBuilder:"+sbr+"---"+System.identityHashCode(str));sbr.append(", China");System.out.println("StringBuilder:"+sbr+"---"+System.identityHashCode(str));}}



执行结果如下:

String:Hello ---33263331
String:Hello World---6413875
String:Hello World, China---21174459
StringBuffer:Hello ---21174459
StringBuffer:Hello World---21174459
StringBuffer:Hello World, China---21174459
StringBuilder:Hello ---21174459
StringBuilder:Hello World---21174459
StringBuilder:Hello World, China---21174459