0

我有几个与这些包装类的方法有关的问题。

首先,为什么 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.
4

4 回答 4

4

鉴于拥有多个方法做同样的事情是没有意义的,不同的方法用不同的参数做不同的事情是合乎逻辑的,一点也不奇怪。

首先,为什么 Long(或 Integer)方法在 valueOf 方法中将 String 作为参数?

所以它可以解析字符串并给你一个LongorInteger作为文档状态。

而是在 toString 方法中采用数字原语?

valueOf 将字符串转换为对象,toString 接受一个值并将其转换为字符串。鉴于这些几乎与您期望的相反的事情相反。

其次,为什么下面列出的第一行代码不起作用(通过将 String 作为第一个参数)而第二行工作正常(通过将 long(或 int)作为第一个参数)。

80是一个有效的十进制数,可以转换为八进制数。 80不是有效的八进制(或二进制),因此您无法将其解析为八进制。

于 2013-02-04T15:20:34.363 回答
3
  1. 这些方法String分别从表示转换和转换为表示。你会期待什么?

  2. 第一行代码调用了一个不带String参数的方法。它转换为 a String,那为什么要输入呢?这是输出

“80”不是有效的八进制数。8 不是八进制的数字。值 8 是“10”。

于 2013-02-04T15:21:15.157 回答
1

Long.valueOf(String, int)将 String 转换为Long.

Long.toString(long. int)将 a 转换long为字符串。

这两个函数都采用用于转换的基数。

Long.toString(long, int)我建议看一下and的 JavaDoc Long.valueof(String, int)。该文档很棒,并且很好地解释了它。

于 2013-02-04T15:35:43.450 回答
1

实际上这两种方法都是绑定的:

/** 
 * Returns the string representation of the <code>long</code> argument. 
 * <p> 
 * The representation is exactly the one returned by the 
 * <code>Long.toString</code> method of one argument. 
 * 
 * @param   l   a <code>long</code>. 
 * @return  a string representation of the <code>long</code> argument. 
 * @see     java.lang.Long#toString(long) 
 */ 
public static String valueOf(long l) { 
    return Long.toString(l, 10); 
}

似乎Long.toString()第一个参数需要很长时间,请参见上面的代码。

于 2013-02-04T15:23:16.307 回答