有很多初学者对string和stringbuffer的问题纠缠不清,不知道什么时候用string什么时候用stringbuffer,无法区别他们的用法,其实根本的原因是他们没有弄清楚这两者的内部的机制以及如何的运作。
public class StringTest {
public static void stringReplace (String text) {
text = text.replace('j' , 'i');
}
public static void bufferReplace (StringBuffer text) {
text = text.append("C");
}
public static void main (String args[]) {
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java");
stringReplace (textString);
bufferReplace (textBuffer);
System.out.println (textString + textBuffer);
}
}
答案是 javajavaC
String是个不可变类,stringbuffer是个可变的类。String的方法都不会改变它本身,改变的是它的引用,指向不同的内存地址;而stringbuffer会改变缓冲区内的字符串内容。
String覆盖了Object类的equals()方法,而stringbuffer没有覆盖了Object类的equals()方法,所以会有一下的结果:
StringBuffer str1 = new StringBuffer("lgl669");
StringBuffer str2 = new StringBuffer("lgl669");
str1.equals(str2)//为什么是false
String str1 = new String("lgl669");
String str2 = new String("lgl669");
str1.equals(str2)//为什么是true
因为没有覆盖equals()方法,StringBuffer 调用Object中的equals()方法,根据引用(地址)进行比较,所以为false;String 重写了equals() 方法,根据值进行比较,所以为true。