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 eitherFormat
objects orString
s. When formatting with objectY
, if the object is aNumberFormat
, then((NumberFormat) Y).format(X)
is called. OtherwiseY.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:
double[] getLimits()
Object[] getFormats()
-- notString[]
!!!
Is this a bug in the API? Should the setter have been declared setChoices(double[], Object[])
开发者_如何学Goinstead, or am I not understanding how to use setChoices
correctly?
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'.
It definitely looks like a bug. formats is assigned directly to a String[] instance variable. Source code.
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
java.text.ChoiceFormat
source code (OpenJDK version)
精彩评论