views:

36

answers:

3

From the java.text.ChoiceFormat API:

setChoices(double[] limits, String[] formats): Set the choices to be used in formatting.

Parameters:

  • limits - contains [...]
  • formats - are the formats you want to use for each limit. They can be either Format objects or Strings. When formatting with object Y, if the object is a NumberFormat, then ((NumberFormat) Y).format(X) is called. Otherwise Y.toString() is called.

I'm having difficulties understanding the documentation for the formats parameter: how can you possibly pass a Format/NumberFormat object to setChoices if it's declared String[] formats?

Note that interestingly, the getters counterpart of setChoices are declared as follows:

Is this a bug in the API? Should the setter have been declared setChoices(double[], Object[]) instead, or am I not understanding how to use setChoices correctly?

A: 

This has been reported and accepted as Bug 6960866.

A String[] can never contain an instanceof Number/NumberFormat; that goes against every OOP subtyping principles.

If you look at the source code, the private field is declared as String[] choiceFormats, so simply declaring setChoices(double[], Object[]) is not an easy fix, and would instead break the code. In fact, looking at the rest of the code, there is no functionality like what the documentation claims: there is no instanceof Number test, no (NumberFormat) cast anywhere in the code.

Thus, given the current state of the source code, the bug is in the documentation, which claims functionality which is neither possible nor actually implemented.

Such functionality would be very nice to have, and probably should exist, but currently it doesn't, so this can also be seen as a bug in the source code, which is missing the implementation.

References

polygenelubricants
A: 

It definitely looks like a bug. formats is assigned directly to a String[] instance variable. Source code.

David F
+1  A: 

You can check the source code

Everywhere mention is made in comments refering to the string/formatter duality, however the implementation only copies strings

e.g. formatting a double :

        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]);
        }

In the return you clearly see it just copies from the stringarray and no attempt to format is done.

I just think that functionality was 'forgotten'.

Peter Tillemans