有没有办法在循环中重用Formatter对象? [英] is there a way to re-use a Formatter object within a loop?

查看:170
本文介绍了有没有办法在循环中重用Formatter对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在循环中重用Formatter或者我只是实例化并让垃圾收集器处理它? (这是一个Java问题)。请注意,如果我将实例化从循环中取出,则循环中先前迭代的格式化内容将被附加到。 Formatter.flush()似乎只是刷新,与其名称相同,并且没有给出允许重复使用清单的好处。

Is there a way to re-use a Formatter in a loop or do I simply instantiate and let the garbage collector deal with it? (This is a Java question). Note if I take instantiation out of the loop, the formatted content of previous iterations through the loop will get appended to. Formatter.flush() only seems to flush, true to its name and does not give the benefit of allowing a clean slate re-use.

示例:

for (...)
{
    Formatter f = new Formatter();
    f.format("%d %d\n", 1, 2);
    myMethod(f.toString());
}


推荐答案

您可以像这样使用它:

StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb);

for (...)
{
    f.format("%d %d\n", 1, 2);
    myMethod(sb.toString());
    sb.setLength(0);
}

这将重用Formatter和StringBuilder,它可能是也可能不是性能为您的用例获得收益。

This will reuse the Formatter and StringBuilder, which may or may not be a performance gain for your use case.

这篇关于有没有办法在循环中重用Formatter对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆