我认为这已经得到了回答,但我似乎无法找到它.
我有一个实例方法,它将一些内容写入输出流
writeTo(OutputStream){
//class specific logic
}
Run Code Online (Sandbox Code Playgroud)
我希望它将这些内容放入StringBuilder中.我可以通过临时文件来做到这一点,但这似乎不对.我想做的事情如下:
Stringbuilder sb = /* */;
OutputStream os = outForStringBuilder(sb);//not sure how to do this
instance.writeTo(os); //This should write the contents to Stringbuilder
Run Code Online (Sandbox Code Playgroud) 我知道String pool是如何工作的.那说:
void doSomething1(){
System.out.println("This string is now added to the string pool and will stay there even after this method returns");
}
void doSomething2(){
String msg = new String("This string is now added to the string pool and will stay there even after this method returns");
System.out.println(msg);
}
Run Code Online (Sandbox Code Playgroud)
是doSomething2不是更好doSomething1.如果一些字符串的可能性非常低,是否应该鼓励这一点reused.我看到的问题是在案例1中,即使不再使用,字符串也会在延长的时间内保持在范围内.