【发布时间】:2018-07-18 02:11:08
【问题描述】:
似乎 parseDouble 可以接受带有尾随空格的字符串,但是 parseInt 和 parseLong 会抛出异常。
例如对于这个测试用例
@Test
public void testNumberParsing() {
try {
Double.parseDouble("123.0 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Integer.parseInt("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
try {
Long.parseLong("123 ");
System.out.println("works");
}catch (NumberFormatException e) {
System.out.println("does not work");
}
}
结果是
works
does not work
does not work
为什么会有不同的行为?这是故意的吗?
【问题讨论】:
-
链接副本中的唯一答案只讨论了这些方法的实现,甚至没有提到这种行为也记录在the JavaDocs
-
简而言之,它的历史——
Integer.parseInt从一开始就存在,Double.parseDouble根据 JavaDocs 是在 1.2 中添加的。我想,要找出这些决定背后的原因需要一些邮件列表考古学。出于向后兼容性的考虑,它们从未更改过。
标签: java