【发布时间】:2011-12-31 16:47:39
【问题描述】:
有没有更简单的方法来理解 java 中多种格式化方式之间的关系?我对以下内容感到困惑:
System.out.printf()
System.out.format()
String.format()
System.console.format()
new Formatter(new StringBuffer("Test")).format();
DecimalFormat.format(value);
NumberFormat.format(value);
以上类/方法是否相关?了解差异以及在哪种情况下使用哪种方法的最佳方法是什么?
例如,System.out.printf、System.out.format 和 String.format 都使用相同的语法和格式标志。我看不出他们三个有什么区别。
谢谢
【问题讨论】:
-
它们只是包装
Formatter功能的便捷方法。 (不确定NumberFormat及其子类如何与之关联,即关系流动的方式。) -
@Dave 但仍然是一个很好的问题,为什么我们确实有
PrintStream.format和PrintStream.printf- afaik 它们是在同一个版本中添加的并且具有相同的功能。 printf 的 jdocs 甚至状态为:An invocation of this method of the form out.printf(format, args) behaves in exactly the same way as the invocation out.format(format, args)。真是奇怪的复制 -
@Voo 我猜有人添加了所有
printf的东西以使format功能更符合print/println等,但这只是一个猜测。由于各种原因,大多数 API 都有一定的重复性——允许不同的风格、不同的意图传达等等。 -
@Dave 是的,我认为那里没有深奥的神秘解释,所以这只是一个见仁见智的问题。我个人尝试在我的 API 中完全避免这些事情——引用 Python 的禅宗
There should be one-- and preferably only one --obvious way to do it.。至少 javadoc 清楚地表明它们是相同的,所以没有人会想知道“区别在哪里?” (至少没有人阅读文档)
标签: java string formatting