java 字符串缓冲区声明

标签 java string memory stringbuilder

当我不包含注释行时,prevLineBuffer 包含“null”。当我包含注释行时,它仍然有效,但打印一个空字符串。 Java 是否为声明的字符串静态分配空间,然后为注释行中的附加字符串动态分配空间?两者似乎都有效...

public class Indexer {
    String input;
    StringBuilder prevLineBuffer;

    Indexer(String inputFileName) throws RuntimeException{
        input = inputFileName;
        //prevLineBuffer = new StringBuilder();
        System.out.print(prevLineBuffer);

    }//constructor
}//class

最佳答案

您需要打印 .toString() 的结果,并为其添加 .append() 内容,以便为其提供打印内容。例如:

    prevLineBuffer = new StringBuilder();
    prevLineBuffer.append(inputFileName);
    System.out.print(prevLineBuffer.toString());

回答你问题的后半部分......

来自String docs :

A pool of strings, initially empty, is maintained privately by the class String. [...] When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

来自StringBuilder docs :

In general, if sb refers to an instance of a StringBuilder, then sb.append(x) has the same effect as sb.insert(sb.length(), x). Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger. -

关于java 字符串缓冲区声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2294294/

相关文章:

java - 使用 Java 正则表达式匹配重复的 HTML 模式

java - 使用值删除 Swing 中的复选框

regex - 如何从字符串中删除和 ID

excel - 检查单元格是否包含 Excel 列表中的子字符串

c++ - 如何使用反斜杠对字符串进行字符串化

c - 如何将 void* pointer1 分配给 void* pointer2?面临一些问题

C# 日期时间堆栈内存

java - 升级到 Android 7 后,LocationListner 不再监听 GPS 状态变化

c - 动态内存/realloc 字符串数组

java - 使用java中的移位将有符号字节数组内容转换为十进制