Java语言中,有4个类可以对字符或字符串进行操作,它们是Character、String、StringBuffer、StringTokenizer,其中Character用于单个字符操作,String用于字符串操作,属于不可变类,而StringBuffer也是用于字符串操作,不同之处是StringBuffer属于可变类。
String是不可变类,也就是说,String对象一旦被创建,其值将不能被改变,而StringBuffer是可变类,当对象被创建后仍然可以对其值进行修改。由于String是不可变类,因此适合在需要被共享的场合中使用,而当一个字符串经常需要被修改时,最好使用StringBuffer来实现。如果用String来保存一个经常被修改的字符串,在字符串被修改时会比StringBuffer多很多附加的操作,同时生成很多无用的对象,由于这些无用的对象会被垃圾回收器来回收,因此会影响程序的性能。
package test;
public class Test{
public static void testString(){
String s="hello";
String s1="world";
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++){
s+=s1;
}
long end=System.currentTimeMillis();
long runTime=(end-start);
System.out.println(runTime);
}
public static void testStringBuffer(){
StringBuffer s=new StringBuffer("Hello");
String s1="world";
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++){
s.append(s1);
}
long end=System.currentTimeMillis();
long runTime=(end-start);
System.out.println(runTime);
}
public static void testStringBuilder(){
StringBuilder s=new StringBuilder("hello");
String s1="world";
long start=System.currentTimeMillis();
for(int i=0;i<10000;i++){
s.append(s1);
}
long end=System.currentTimeMillis();
long runTime=(end-start);
System.out.println(runTime);
}
public static void main(String[] args){
testString();
testStringBuffer();
testStringBuilder();
}
}
程序运行结果为:
265
16
0
从运行结果中看,当一个字符串经常被修改时,使用StringBuffer比使用String好的多。
StringBuilder也可以被修饰的字符串,它与StringBuffer类似,都是字符串缓冲区,但是StringBuilder不是线程安全的,如果只是单线程中使用字符串缓冲区,那么StringBuilder的效率会更高些。因此在只有单线程访问时可以使用StringBuilder,当有多个现成访问时,最好使用线程安全的StringBuffer。因为StringBuffer必要时可以对这些方法进行同步,所以任意特定实例上的所有操作就好像是以串行顺序发生的,该顺序与所涉及的每个线程进行的方法调用顺序一致。
在执行效率方面,StringBuilder最高,StringBuffer次之,String最低。
StringTokenizer是用来分割字符串的工具类,示例如下:
package test;
import java.util.StringTokenizer;
public class Test{
public static void main(String args[]){
StringTokenizer st=new StringTokenizer("Welcome to our country");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}