java int.tryparse,Java是否具有不会为不良数据引发异常的int.tryparse?

博客讨论了Java中Integer.parseInt方法对无效数据会抛出异常影响性能的问题。提出解决方案,可自定义tryParseInt方法,通过捕获异常判断能否解析;还给出了更优的tryParse方法,可指定默认值,且支持单字符串参数重载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The great thing with this method is that it doesn't throw an exception for bad data.

In java, Integer.parseInt("abc") will throw an exception, and in cases where this may happen a lot performance will suffer.

Is there a way around this somehow for those cases where performance is an issue?

The only other way I can think of is to run the input against an regex, but I have to test to see what is faster.

解决方案

No. You have to make your own like this:

boolean tryParseInt(String value) {

try {

Integer.parseInt(value);

return true;

} catch (NumberFormatException e) {

return false;

}

}

...and you can use it like this:

if (tryParseInt(input)) {

Integer.parseInt(input); // We now know that it's safe to parse

}

EDIT (Based on the comment by @Erk)

Something like follows should be better

public int tryParse(String value, int defaultVal) {

try {

return Integer.parseInt(value);

} catch (NumberFormatException e) {

return defaultVal;

}

}

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {

return tryParse(value, 0)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值