java.lang.LString,Long.valueOf(java.lang.String)和new Long(java.lang.String)之间的区别?...

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.

Coder #1 has done this:

String strId = "12345678";

...

Long lId = new Long(strId);

While coder #2 has done this:

String strId = "12345678";

...

Long lId = Long.valueOf(strId);

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.

Is there any functional difference between passing the string in the constructor and using Long.valueOf()? I've checked the constructor doc here:

and the docs for valueOf() here:

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!

解决方案

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].

So, you should prefer Long.valueOf method, because it may save you some memory.

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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值