在JAVA中,字符串使用String类进行表示,虽然针对String直接操作很方便,但是由于字符串变量声明后不可改变,能改变的只是字符串对象的指向。换言之,不同的字符串常量会占用不同的内存空间,而在频繁修改的字符串操作上,不适用String类型,此时可以使用StringBuffer类型。也就是说该类型方便用户进行内容的修改。
public class Demo {
public static void main(String[] args) throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("Hello").append(" world").append("!");
func(buf);
System.out.println(buf);
}
public static void func(StringBuffer tmp) {
tmp.append("\n").append("hahahha");
}
}
执行结果为:
Hello world!
hahahha
从上面的操作来看,StringBuffer的字符串连接操作可以使用append方法实现,其返回值也应该是StringBuffer类型,因此才能够实现append的串联。而StringBuffer类型不能使用+进行字符串拼接。
但是在开发中String类的使用频率是要比StringBuffer高的多的,这意味着StringBuffer最好在字符串频繁发生修改的时候使用,毕竟String的使用方法相较于StringBuffer来说还是更简单的。
// String
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence, Constable, ConstantDesc
// StringBuffer
public final class StringBuffer
extends Object
implements Serializable, Comparable<StringBuffer>, CharSequence
通过上述String和StringBuffer的定义来看,两者都是抽象接口CharSequence的子类,这样的话可以利用向上转型进行参数转换:
public class Demo {
public static void main(String[] args) throws Exception {
StringBuffer buf = new StringBuffer();
buf.append("Hello").append(" world").append("!");
String str = "Hello world!";
func(buf);
func(str);
}
public static void func(CharSequence tmp) {
System.out.println(tmp);
}
}
执行结果为:
Hello world!
Hello world!
从上面的例子来看,可以使用CharSequence接收String和StringBuffer对象,进行适配。
而String和StringBuffer都和字符串操作有关系,那么两者能否实现转换,可以使用以下转换方式:
public StringBuffer(String str)
public StringBuffer(CharSequence seq)
public String(StringBuffer buffer)
那么就可以:
public class Demo {
public static void main(String[] args) throws Exception {
String str = "Hello world!";
StringBuffer buf = new StringBuffer(str);
String str1 = buf.toString();
String str2 = new String(buf);
System.out.println(buf);
System.out.println(str1);
System.out.println(str2);
}
}
执行结果为:
Hello world!
Hello world!
Hello world!
从上面的结果来看,可以使用StringBuffer和String的构造方法进行互相转换,而使用StringBuffer的toString方法可以转换为String方法。
String和StringBuffer类型也都是Comparable接口的子类,也就是说可以实现同类型的相互比较,但是String和StringBuffer之间应该怎么比较:
public class Demo {
public static void main(String[] args) throws Exception {
String str = "Hello world!";
StringBuffer buf = new StringBuffer("Hello world!");
System.out.println(str.contentEquals(buf));
}
}
执行结果为:
true
也就是说,可以使用String类型的contentEquals方法进行内容上的比较。
而至于StringBuffer也提供了很多方法:
StringBuffer append(boolean b) // Appends the string representation of the boolean argument to the sequence.
StringBuffer append(char c) // Appends the string representation of the char argument to this sequence.
StringBuffer append(char[] str) // Appends the string representation of the char array argument to this sequence.
StringBuffer append(char[] str, int offset, int len) // Appends the string representation of a subarray of the char array argument to this sequence.
StringBuffer append(double d) // Appends the string representation of the double argument to this sequence.
StringBuffer append(float f) // Appends the string representation of the float argument to this sequence.
StringBuffer append(int i) // Appends the string representation of the int argument to this sequence.
StringBuffer append(long lng) // Appends the string representation of the long argument to this sequence.
StringBuffer append(CharSequence s) // Appends the specified CharSequence to this sequence.
StringBuffer append(CharSequence s, int start, int end) // Appends a subsequence of the specified CharSequence to this sequence.
StringBuffer append(Object obj) // Appends the string representation of the Object argument.
StringBuffer append(String str) // Appends the specified string to this character sequence.
StringBuffer append(StringBuffer sb) // Appends the specified StringBuffer to this sequence.
StringBuffer appendCodePoint(int codePoint) // Appends the string representation of the codePoint argument to this sequence.
int capacity() // Returns the current capacity.
char charAt(int index) // Returns the char value in this sequence at the specified index.
IntStream chars() // Returns a stream of int zero-extending the char values from this sequence.
int codePointAt(int index) // Returns the character (Unicode code point) at the specified index.
int codePointBefore(int index) // Returns the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, int endIndex) // Returns the number of Unicode code points in the specified text range of this sequence.
IntStream codePoints() // Returns a stream of code point values from this sequence.
int compareTo(StringBuffer another) // Compares two StringBuffer instances lexicographically.
StringBuffer delete(int start, int end) // Removes the characters in a substring of this sequence.
StringBuffer deleteCharAt(int index) // Removes the char at the specified position in this sequence.
void ensureCapacity(int minimumCapacity) // Ensures that the capacity is at least equal to the specified minimum.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) // Characters are copied from this sequence into the destination character array dst.
int indexOf(String str) // Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex) // Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
StringBuffer insert(int offset, boolean b) // Inserts the string representation of the boolean argument into this sequence.
StringBuffer insert(int offset, char c) // Inserts the string representation of the char argument into this sequence.
StringBuffer insert(int offset, char[] str) // Inserts the string representation of the char array argument into this sequence.
StringBuffer insert(int index, char[] str, int offset, int len) // Inserts the string representation of a subarray of the str array argument into this sequence.
StringBuffer insert(int offset, double d) // Inserts the string representation of the double argument into this sequence.
StringBuffer insert(int offset, float f) // Inserts the string representation of the float argument into this sequence.
StringBuffer insert(int offset, int i) // Inserts the string representation of the second int argument into this sequence.
StringBuffer insert(int offset, long l) // Inserts the string representation of the long argument into this sequence.
StringBuffer insert(int dstOffset, CharSequence s) // Inserts the specified CharSequence into this sequence.
StringBuffer insert(int dstOffset, CharSequence s, int start, int end) // Inserts a subsequence of the specified CharSequence into this sequence.
StringBuffer insert(int offset, Object obj) // Inserts the string representation of the Object argument into this character sequence.
StringBuffer insert(int offset, String str) // Inserts the string into this character sequence.
int lastIndexOf(String str) // Returns the index within this string of the last occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex) // Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
int length() // Returns the length (character count).
int offsetByCodePoints(int index, int codePointOffset) // Returns the index within this sequence that is offset from the given index by codePointOffset code points.
StringBuffer replace(int start, int end, String str) // Replaces the characters in a substring of this sequence with characters in the specified String.
StringBuffer reverse() // Causes this character sequence to be replaced by the reverse of the sequence.
void setCharAt(int index, char ch) // The character at the specified index is set to ch.
void setLength(int newLength) // Sets the length of the character sequence.
CharSequence subSequence(int start, int end) // Returns a new character sequence that is a subsequence of this sequence.
String substring(int start) // Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start, int end) // Returns a new String that contains a subsequence of characters currently contained in this sequence.
String toString() // Returns a string representing the data in this sequence.
void trimToSize() // Attempts to reduce storage used for the character sequence.
从上面提供的方法来看,有很多方法是和String中的方法类似的。
而除了StringBuffer之外,JAVA还提供了StringBuilder类,不过该类是同步的,属于安全的线程操作。