我想知道StringBuilder和StringBuffer之间的区别.在StringBuffer中,它自动分配16个字符.当我们添加一个字符串"hello"时,它的容量增加到21.可以有人澄清我的怀疑吗?
我在 Java 中尝试了 StringBuffer 类的构造函数,但我对 StringBuffer(int initial ) 构造函数的工作感到困惑。
我知道它为缓冲区提供了初始容量,但我怀疑,当提供的初始容量实际上小于对象的长度时,在这种情况下容量如何增加?
我尝试了两种情况,在第一种情况下:
StringBuffer str = new StringBuffer(11);
str.append("Hello World!");
System.out.println(str.length() + " " + str.capacity()); //prints 12 24
Run Code Online (Sandbox Code Playgroud)
即容量变为字符串长度的两倍。
在第二个:
StringBuffer str = new StringBuffer(10);
str.append("Hello World!");
System.out.println(str.length() + " " + str.capacity()); //prints 12 22
Run Code Online (Sandbox Code Playgroud)
即容量变为长度 + 初始缓冲容量
那么为什么缓冲区大小会有如此不同的增加。在这两种情况下,初始容量都小于字符串长度,因此在两种情况下它都应该加倍到长度变为 24,或者加起来等于初始缓冲区,在第一种情况下变为 23,在第二种情况下变为 22。我也阅读了文档和其他各种博客,但我能找到的只是 StringBuffer 类的构造函数和函数的基本用法。
请帮帮我。谢谢你。
我需要将StringBuffer数组转换为String数组进行排序.Java中有任何方法吗?
下面是我的代码,我试图按字母顺序对值(input1)进行排序,其中包含第一个字母为UpperCase并忽略其他值.
import java.util.*;
public class IPLMatch
{
public static void main(String args[])
{
int input1 = 4;
String input2[] = {"One","two","Three","foUr"}, output[];
StringBuffer[] temp = new StringBuffer[input1];
int j = 0, k = 0;
for(int i = 0; i < input1; i++)
{
boolean isUpperCase = Character.isUpperCase(input2[i].charAt(0));
if(isUpperCase)
{
temp[j++] = new StringBuffer(input2[i]);
}
}
//I need convert my stringbuffer array (temp) to String array for sorting
Arrays.sort(temp);
System.out.print("{");
for(int i = 0; i < temp.length; i++)
{
System.out.print( …Run Code Online (Sandbox Code Playgroud) 我现在正在做一个Java项目,并且觉得StringBuffer在执行这个特定任务时会有很多帮助,我正在"构建"Matrix的字符串表示:
/**
* Returns a String representation of the Matrix using the getIJ getter
* function. You should use MaF.dF to format the double numbers to a
* sensible number of decimal places and place the numbers in columns.
*
* @return A String representation of the Matrix
*/
public String toString() {
//String stringBuilder = new String
StringBuffer beep = new StringBuffer;
for(i=0; i<m-1; i++){
for(j=0; j<n-1; j++){
}
// You need to fill in this method
}
Run Code Online (Sandbox Code Playgroud)
我已经在Java程序中尝试了它本身似乎没问题,但后来我在线尝试了一些示例Java程序并且没有编译.是 …