示例 1: Java 程序使用 delete() 使用 StringBuffer 进行清除
class Main { public static void main(String[] args) { // create a string buffer StringBuffer str = new StringBuffer(); // add string to string buffer str.append("Java"); str.append(" is"); str.append(" popular."); System.out.println("StringBuffer: " + str); // clear the string // using delete() str.delete(0, str.length()); System.out.println("Updated StringBuffer: " + str); } }
输出
StringBuffer: Java is popular. Updated StringBuffer:
在上面的例子中,我们使用了
StringBuffer
类的
delete()
方法来清除字符串缓冲区。
这里,
delete()
方法删除指定索引号内的所有字符。
示例 2: 使用 setLength() 清除 StringBuffer
class Main { public static void main(String[] args) { // create a string buffer StringBuffer str = new StringBuffer(); // add string to string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: " + str); // clear the string // using setLength() str.setLength(0); System.out.println("Updated StringBuffer: " + str); } }
输出
StringBuffer: Java is awesome. Updated StringBuffer
此处,
setLength()
方法将
StringBuffer
中存在的字符序列更改为新的字符序列。并且,将新字符序列的长度设置为 0。
因此,旧的字符序列被垃圾收集。
注意: setLength() 方法完全忽略字符串缓冲区中存在的字符序列。但是,delete() 方法访问字符序列并将其删除。因此,setLength() 比 delete() 更快。
示例 3: 通过创建新对象清除 StringBuffer
class Main { public static void main(String[] args) { // create a string buffer StringBuffer str = new StringBuffer(); // add string to string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: " + str); // clear the string // using new // here new object is created and assigned to str str = new StringBuffer(); System.out.println("Updated StringBuffer: " + str); } }
输出
StringBuffer: Java is awesome. Updated StringBuffer:
此处,
new StringBuffer()
创建一个新的字符串缓冲区对象并将前一个变量分配给新对象。在这种情况下,前一个对象将在那里。但它将无法访问,因此将被垃圾收集。
因为,每次不是清除之前的字符串缓冲区,而是创建一个新的字符串缓冲区。因此在性能方面效率较低。