【发布时间】:2013-02-04 15:17:12
【问题描述】:
我有几个与这些包装类的方法有关的问题。
首先,为什么Long(或Integer)方法在valueOf方法中需要一个String作为参数?而是在 toString 方法中采用数字原语? (见下面的例子)
其次,为什么下面列出的第二行代码不起作用(通过将 String 作为第一个参数)而第一行工作正常(通过将 long(或 int)作为第一个参数)。
这两种方法都应该分别以 String 和 Long 类型返回第一个参数中声明的值,该值转换为第二个参数中指定的基数(在本例中为 8)。
String s = Long.toString(80,8)// takes a numeric primitive and it works fine.
Long l = Long.valueOf("80",8)// takes a string as first argument it does not compile,
//(as it was because in radix 8 cannot "read" the number 8
// and therefore it prompts an NumberFormatException.
【问题讨论】:
-
A NumberFormatException 不是编译错误。你说得对,80 不是有效的八进制数。
-
因为这些方法本质上是相反的?
-
@SeanOwen 是的,我更正了,我粘贴错了
-
好的,我通过以下测试了解了问题所在: Long l1 = Long.valueOf("70",8);字符串 s1 = Long.toString(70,8); System.out.println(l1+ " "+s1);我看到它实际上以两种不同的方式处理这些信息。现在它是有道理的。不过感谢您的及时答复。