When using NumberFormat.getInstance()
, and print hashCode()
like below there are always the same.
val twoFractionDigitsFormat: NumberFormat by lazy {
NumberFormat.getInstance().apply {
minimumFractionDigits = 2
maximumFractionDigits = 2
roundingMode = RoundingMode.HALF_UP
}
}
val fourFractionDigitsFormat: NumberFormat by lazy {
NumberFormat.getInstance().apply {
minimumFractionDigits = 4
maximumFractionDigits = 4
roundingMode = RoundingMode.HALF_UP
}
}
Then print
println(NumberFormat.getInstance().hashCode())
println(fourFractionDigitsFormat.hashCode())
println(twoFractionDigitsFormat.hashCode())
The output are:
423132
423132
423132
If check the source code, the getInsstance()
calls
DecimalFormat numberFormat = new DecimalFormat(numberPatterns[entry], symbols);
to create a DecimalFormat
every time. These should be not the same instance. Which also be provided by ===
returns false
.
Check hashCode()
method:
@Override
public int hashCode() {
return maximumIntegerDigits * 37 + maxFractionDigits;
// just enough fields for a reasonable distribution
}
This maximumIntegerDigits * 37 + maxFractionDigits;
always return same value. And maximumFractionDigits
is public, maxFractionDigits
is private.
Here is the quotation:
/**
* The maximum number of digits allowed in the fractional portion of a
* number. {@code maximumFractionDigits} must be greater than or equal to
* {@code minimumFractionDigits}.
* <p>
* <strong>Note:</strong> This field exists only for serialization
* compatibility with JDK 1.1. In Java platform 2 v1.2 and higher, the new
* {@code int} field {@code maximumFractionDigits} is used instead.
* When writing to a stream, {@code maxFractionDigits} is set to
* {@code maximumFractionDigits} or {@code Byte.MAX_VALUE},
* whichever is smaller. When reading from a stream, this field is used
* only if {@code serialVersionOnStream} is less than 1.
*
* @serial
* @see #getMaximumFractionDigits
*/
private byte maxFractionDigits = 3;
Then my question is the hashCode()
is always the same(if you don’t change maximumIntegerDigits), then how ===
works, is it a bug?
Thanks!