StringBuffer和StringBuilder的区别
StringBuffer
* A thread-safe, mutable sequence of characters.
* A string buffer is like a {@link String}, but can be modified. At any
* point in time it contains some particular sequence of characters, but
* the length and content of the sequence can be changed through certain
* method calls.
StringBuffer是线程安全的,可变字符序列。
StringBuffer像String,但是可以被修改。
常用的方法:
1.length():返回字符串的数量。
public int length() {
return count;
}
2.StringBuffer构造函数
初始化函数,StringBuffer的容量是初始的参数的长度+16.
/**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
@HotSpotIntrinsicCandidate
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
3.根据索引得到字符
/**
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see #length()
*/
@Override
public synchronized char charAt(int index) {
return super.charAt(index);
}
如何使用:如下
StringBuffer sb = new StringBuffer("ABCEDFG");
System.out.println(sb.charAt(1));
每天进步一点
浙公网安备 33010602011771号