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 capabl开发者_运维技巧e 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 IOException
if you call the format
method yourself, it throws only unchecked exceptions. Just change your code slightly:
StringBuilder builder = new StringBuilder();
Formatter f = new Formatter(builder);
for (...) {
f.format("%s %d\n", entry.getKey(), entry.getValue());
}
return builder.toString();
Your question was "How not to have to catch the exception?".
Straight answer:
((StringBuilder) f.out()).append(entry.getKey().asString() + " ");
Why would that work? Because new Formatter() creates a StringBuilder object as the destination, whereas f.out() returns this destination. The append() method of StringBuilder does not declare an exception.
Moreover I don't get, what you're trying to accomplish with that code. Since you call append() on the destination of the Formatter you're actually circumventing the Formatter and appending directly to the destination. So the only use of the Formatter is the call to
f.format("%s %d\n", thing1, thing2);
If KeyType
and ValueType
are your own-defined classes, why don't you override toString()
in those two classes? Then you can simply do
StringBuffer buf = new StringBuffer();
for (Entry<KeyType, ValueType> entry: map.entrySet()) {
buf.append(entry.getKey().toString())
.append(entry.getValue().toString())
.append("\n");
}
return buf.toString();
How about Something like this...
String methodToYieldMyInstanceAsString()
{
StringBuilder sb = new StringBuilder();
sb.append(String.format("%s %d\n", thing1, thing2));
for (Entry<KeyType, ValueType> entry: map.entrySet())
{
String key = entry.getKey().toString();
String value = entry.getValue().toString();
sb.append(key).append(value);
}
return sb.toString();
}
精彩评论