等于字符串文字和来自NumberFormat的字符串因字节表示不同而失败

xiu*_*teo 9 java java-9

我用prod代码玩Java 9.我发现一些格式化测试失败了.经过一些研究,我能够创建一个类来重现这个问题.这种情况发生在Java 9中,而不是Java 8中.

该课程在这里 https://pastebin.com/87sA5WMb

import java.text.*;
import java.util.*;

public class FormatFails {
    public static void main(String... args){

        Currency currency = Currency.getInstance("EUR");
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
        currencyFormatter.setMaximumFractionDigits(0);
        currencyFormatter.setMinimumFractionDigits(0);
        currencyFormatter.setCurrency(currency);

        String expected = "123 457 €";
        String obtained = currencyFormatter.format(123456.789);
        System.out.println(expected);
        System.out.println(obtained);
        System.out.println(expected.equals(obtained));

        System.out.format("Bytes from expected: %s\n",Arrays.toString(expected.getBytes()));
        System.out.format("Bytes from obtained: %s\n",Arrays.toString(obtained.getBytes()));       
    }

}
Run Code Online (Sandbox Code Playgroud)

基本上比较2个字符串:

  • 一个字符串文字和
  • Locale.FRANCE中使用NumberFormat生成的格式化字符串

因为以下原因,在两者上使用equals失败:

123 457 €
123 457 €
false
Bytes from expected: [49, 50, 51, -62, -96, 52, 53, 55, 32, -30, -126, -84]
Bytes from obtained: [49, 50, 51, -62, -96, 52, 53, 55, -62, -96, -30, -126, -84]
Run Code Online (Sandbox Code Playgroud)

如您所见,有不同的字节数和不同的表示.我不知道如何解决这个问题,更重要的是Java9中影响代码的变化.

使用普通旧Java 8的结果如下:

123 457 €
123 457 €
true
Bytes from expected: [49, 50, 51, -62, -96, 52, 53, 55, 32, -30, -126, -84]
Bytes from obtained: [49, 50, 51, -62, -96, 52, 53, 55, 32, -30, -126, -84]
Run Code Online (Sandbox Code Playgroud)

使用Java 9版本

java version "9"
Java(TM) SE Runtime Environment (build 9+181)
Java HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)
Run Code Online (Sandbox Code Playgroud)

这是最新版本.

Ala*_*man 7

默认情况下,JDK 9已移至使用CDLR区域设置数据.有关JEP的链接及其更多信息,请参阅JDK 9发行说明(请参阅http://jdk.java.net/9/release-notes#JDK-8008577).可以使用发行说明和JEP文档系统属性来配置JDK以在需要时使用旧版JRE语言环境数据.