ChoiceFormat.setChoices关于格式参数类型和文档的混淆

时间:2010-06-12 09:20:36

标签: java string formatting polymorphism number-formatting

来自java.text.ChoiceFormat API:

  

setChoices(double[] limits, String[] formats):设置格式化时使用的选项。

     

参数:

     
      
  • limits - 包含[...]
  •   
  • formats - 是您要为每个限制使用的格式。它们可以是Format个对象,也可以是String个。使用对象Y进行格式化时,如果对象是NumberFormat,则调用((NumberFormat) Y).format(X)。否则调用Y.toString()
  •   

我很难理解formats参数的文档:如果Format/NumberFormat声明为setChoices,如何将String[] formats对象传递给setChoices

请注意,有趣的是,String[]的getter对应方声明如下:

这是API中的错误吗?是否应该将setter声明为setChoices,或者我不理解如何正确使用{{1}}?

3 个答案:

答案 0 :(得分:1)

您可以查看the source code

无处不在提及引用字符串/格式化程序二元性的注释中,但实现仅复制字符串

e.g。格式化双精度:

        public StringBuffer format(double number, StringBuffer toAppendTo,
                FieldPosition status) {
            // find the number
            int i;
            for (i = 0; i < choiceLimits.length; ++i) {
                if (!(number >= choiceLimits[i])) {
                    // same as number < choiceLimits, except catchs NaN
                    break;
                }
            }
            --i;
            if (i < 0)
                i = 0;
            // return either a formatted number, or a string
            return toAppendTo.append(choiceFormats[i]);
        }

在回程中你清楚地看到它只是从stringarray复制而没有尝试格式化。

我只是认为功能被'遗忘'。

答案 1 :(得分:0)

此报告已被报告为Bug 6960866

String[]永远不能包含instanceof Number/NumberFormat;这违背了每个OOP子类型原则。

如果您查看源代码,private字段将声明为String[] choiceFormats,因此只需声明setChoices(double[], Object[])不是一个简单的修复,而是会破坏代码。事实上,查看其余的代码,没有像文档声明的那样的功能:代码中没有instanceof Number测试,没有(NumberFormat)转换。

因此,鉴于源代码的当前状态,该错误存在于文档中,该文档声称既不可能也不实际实现的功能。

这样的功能非常好,并且可能应该存在,但目前它不存在,所以这也可以被视为源中的错误代码,它缺少实现。

参考

答案 2 :(得分:0)

它绝对看起来像一个bug。格式直接分配给String []实例变量。 Source code

相关问题