Long.valueOf(java.lang.String)和new Long(java.lang.String)之间的区别? [英] Difference between Long.valueOf(java.lang.String) and new Long(java.lang.String)?
问题描述
我正在合并由两个不同的人编写的代码,并注意到将String值转换为Long已经以两种不同的方式完成。
I'm consolidating code written by two different people and notice that casting a String value into a Long has been done in two different ways.
编码器#1已执行此操作:
Coder #1 has done this:
String strId = "12345678";
...
Long lId = new Long(strId);
编码器#2已执行此操作:
While coder #2 has done this:
String strId = "12345678";
...
Long lId = Long.valueOf(strId);
在功能上,代码操作完全相同。每个位周围都有一个try / catch块来处理抛出的任何 NumberFormatException
。传入的字符串值是一个表示小数的8位字符串:12345678
,在这两种情况下,它都会正确转换为 Long
。
Functionally, the code operates exactly the same. There's a try/catch block around each bit to handle any NumberFormatException
that is thrown. The incoming string value is an 8 digit string that represents a decimal: "12345678"
and in both cases it is correctly converted into Long
.
在构造函数中传递字符串和使用Long.valueOf()之间有什么功能上的区别吗?我在这里检查了构造函数doc:
Is there any functional difference between passing the string in the constructor and using Long.valueOf()? I've checked the constructor doc here:
和valueOf的文档():
and the docs for valueOf() here:
Long.valueOf(java.lang.String)
据我所知,两者都调用parseLong(),所以它不要紧,哪个是使用。我只是想确保我不为自己设置一些奇怪的行为进一步下来的道路。还有,是风格更正确(哈哈)比另一个?非常感谢!
As far as I can tell, they both call parseLong() so it doesn't matter which is used. I just want to make sure I'm not setting myself up for some strange behavior further down the road. Also, is either style more "correct" (haha) than the other? Thanks!
推荐答案
/ code>你将总是创建一个新对象,而使用 Long.valueOf()
,可能会返回缓存的值 long
如果值在 [ - 128到127]
之间。
The difference is that using new Long()
you will always create a new object, while using Long.valueOf()
, may return you the cached value of long
if the value is between [-128 to 127]
.
优先 Long.valueOf
方法,因为它可能会节省一些内存。
So, you should prefer Long.valueOf
method, because it may save you some memory.
如果您看到 Long.valueOf(String)
,它内部调用 Long.valueOf(long)
,其源代码我已经发布如下: -
If you see the source code for Long.valueOf(String)
, it internally invokes Long.valueOf(long)
, whose source code I have posted below: -
public static Long valueOf(String s) throws NumberFormatException
{
return Long.valueOf(parseLong(s, 10));
}
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
这篇关于Long.valueOf(java.lang.String)和new Long(java.lang.String)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!