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