StringBuffer类的trimToSize()方法是一种内置方法,用于修剪用于StringBuffer对象的字符序列的容量。如果StringBuffer对象使用的缓冲区大于保留其当前字符序列所需的缓冲区,则将调用此方法以调整StringBuffer对象的大小,以将该对象转换为空间效率更高的对象。调用此方法可能会(但不是必须)影响以后对capacity()方法的调用返回的值。
用法:
public void trimToSize()
返回值:此方法不返回任何内容。
以下示例程序旨在说明StringBuffer.trimToSize()方法:
示例1:
// Java program to demonstrate
// the trimToSize() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer str
= new StringBuffer("GeeksForGeeks");
// add more string to StringBuffer
str.append("Contribute");
// print capacity
System.out.println("Capacity before "
+ "applying trimToSize() = "
+ str.capacity());
// applying trimToSize() Method
str.trimToSize();
// print string
System.out.println("String = " + str.toString());
// print capacity
System.out.println("Capacity after"
+ " applying trimToSize() = "
+ str.capacity());
}
}
输出:
Capacity before applying trimToSize() = 29 String = GeeksForGeeksContribute Capacity after applying trimToSize() = 23
示例2:
// Java program to demonstrate
// the trimToSize() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer str
= new StringBuffer();
// add more string to StringBuffer
str.append("GeeksForGeeks classes");
// print capacity
System.out.println("Capacity before"
+ " applying trimToSize() = "
+ str.capacity());
// applying trimToSize() Method
str.trimToSize();
// print string
System.out.println("String = " + str.toString());
// print capacity
System.out.println("Capacity after "
+ "applying trimToSize() = "
+ str.capacity());
}
}
输出:
Capacity before applying trimToSize() = 34 String = GeeksForGeeks classes Capacity after applying trimToSize() = 21
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#trimToSize()
相关用法
- Java StringBuilder trimToSize()用法及代码示例
- Java StringBuffer getChars()用法及代码示例
- Java StringBuffer setCharAt()用法及代码示例
- Java StringBuffer offsetByCodePoints()用法及代码示例
- Java StringBuffer toString()用法及代码示例
- Java StringBuffer codePointAt()用法及代码示例
- Java StringBuffer ensureCapacity()用法及代码示例
- Java StringBuffer lastIndexOf()用法及代码示例
- Java StringBuffer substring()用法及代码示例
- Java StringBuffer reverse()用法及代码示例
- Java StringBuffer delete()用法及代码示例
- Java StringBuffer codePointCount()用法及代码示例
- Java StringBuffer replace()用法及代码示例
- Java StringBuffer deleteCharAt()用法及代码示例
- Java StringBuffer indexOf()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuffer trimToSize() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。