当我不包含注释行时,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.
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/