Integer.parseInt()的好方法 [英] Good way to encapsulate Integer.parseInt()
问题描述
Integer.parseInt()
将String转换为int。当某些事情出错(例如, String
不是一个数字,而是字母 a
或其他方式)会抛出异常。但是,如果我必须处理我的代码中的异常,这很快就开始看起来很丑陋。我想把它放在一个方法中,但是,我不知道如何返回一个干净的值,以显示转换出错了。 在C ++中,我可以创建一个接受int指针的方法,让方法本身返回true或false。但是,据我所知,这在Java中是不可能的。我也可以创建一个包含true / false变量和转换值的对象,但这似乎也不是理想的。同样的事情也是一个全球性的价值,这可能会给我一些麻烦的多线程。
这样做有一个干净的方法吗?
您可以返回一个整数
而不是 int
,在解析失败时返回 null
。
这是一个可耻的Java不提供一种这样做的方法,而不会在内部抛出异常 - 你可以隐藏异常(通过捕获它并返回null),但是如果你正在解析数十万位的用户提供的数据。
编辑:这种方法的代码:
public static Integer tryParse(String text){
try {
return Integer.parseInt(text);
} catch(NumberFormatException e){
return null;
}
}
请注意,我不确定如果 text
为空,我的头会做什么。你应该考虑 - 如果它代表一个错误(即你的代码可能会传递一个无效的值,但绝对不能通过null),则抛出一个异常是适当的;如果它不代表一个错误,那么你应该可以像任何其他无效值一样返回null。
最初这个答案使用了 new Integer(String)
构造函数;它现在使用 Integer.parseInt
和一个拳击操作;以这种方式,小值将最终被加载到缓存的整数
对象中,使其在这些情况下更有效。
I have a project in which we often use Integer.parseInt()
to convert a String to an int. When something goes wrong (for example, the String
is not a number but the letter a
, or whatever) this method will throw an exception. However, if I have to handle exceptions in my code everywhere, this starts to look very ugly very quickly. I would like to put this in a method, however, I have no clue how to return a clean value in order to show that the conversion went wrong.
In C++ I could have created a method that accepted a pointer to an int and let the method itself return true or false. However, as far as I know, this is not possible in Java. I could also create an object that contains a true/false variable and the converted value, but this does not seem ideal either. The same thing goes for a global value, and this might give me some trouble with multithreading.
So is there a clean way to do this?
You could return an Integer
instead of an int
, returning null
on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text
is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String)
constructor; it now uses Integer.parseInt
and a boxing operation; in this way small values will end up being boxed to cached Integer
objects, making it more efficient in those situations.
这篇关于Integer.parseInt()的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!