Is there a better way to build strings with formatting and appending than this example? This is a Java question.
Edit: It seems that it would be better if Formatter() was capable of being more like StringBuilder() or that StringBuilder() be capable of being like Formatter(). I especially do not like having to catch an exception given that this is merely a “toString” kind of method, that is to say, trivial. Also, what if I want to append an integer via %d after the loop?
String methodToYieldMyInstanceAsString()
{
Formatter f = new Formatter();
f.format("%s %d\n", thing1, thing2);
for (Entry<KeyType, ValueType> entry: map.entrySet())
{
try
{
f.out().append(entry.getKey().asString() + " ");
f.out().append(entry.getValue().asString() + "\n");
}
catch (IOException e)
{
throw new RuntimeException();
}
}
return f.toString();
}
One good thing about this code is that I only use one Formatter object, for what it’s worth.
You can avoid the
IOExceptionif you call theformatmethod yourself, it throws only unchecked exceptions. Just change your code slightly: